如何正确地按日期对列表进行排序



我试图对数据列表进行排序,但排序似乎不起作用。我首先取出列表中的日期部分,并尝试将其与当前日期进行比较。

from datetime import datetime, date
test = {
'3001265': ['Samsung', 'phone', '1200', '12/1/2023', ''],
'1009453': ['Lenovo', 'tower', '599', '10/1/2020', ''],
'1167234': ['Apple', 'phone', '534', '2/1/2021', ''],
'2390112': ['Dell', 'laptop', '799', '7/2/2020', ''],
'9034210': ['Dell', 'tower', '345', '5/27/2020', ''],
'7346234': ['Lenovo', 'laptop', '239', '9/1/2020', 'damaged'],
'2347800': ['Apple', 'laptop', '999', '7/3/2020', '']
}
test_dates = []
for value, index in test.items():
if index[3] not in test_dates:
test_dates.append(index[3])
test_day = []
today = date.today()
for date in test_dates:
other_date = datetime.date(datetime.strptime(date, '%m/%d/%Y'))
if other_date < today:
other_date = other_date.strftime('X%m/X%d/%Y').replace('X0','X').replace('X','')
test_day.append(other_date)
print(test_day)
table = range(len(test_day))
for num in table:
entry_list = []
for row, entry in test.items():
entry = [row] + entry
for line in entry:
if test_day[num] in line:
entry_list.append(entry)
sorted_entry = sorted(entry_list, key=lambda x: x[4])
for object in sorted_entry:
print(object)

我的目标是找到今天之前的所有日期,并输出按日期排序的所有信息。这是输出:

['1009453', 'Lenovo', 'tower', '599', '10/1/2020', '']
['2390112', 'Dell', 'laptop', '799', '7/2/2020', '']
['9034210', 'Dell', 'tower', '345', '5/27/2020', '']
['7346234', 'Lenovo', 'laptop', '239', '9/1/2020', 'damaged']
['2347800', 'Apple', 'laptop', '999', '7/3/2020', '']

理想的输出是按日期或第4列排序的行:

['9034210', 'Dell', 'tower', '345', '5/27/2020', '']
['2390112', 'Dell', 'laptop', '799', '7/2/2020', '']
['2347800', 'Apple', 'laptop', '999', '7/3/2020', '']
['7346234', 'Lenovo', 'laptop', '239', '9/1/2020', 'damaged']
['1009453', 'Lenovo', 'tower', '599', '10/1/2020', '']

错误的原因是使用字符串而不是时间进行排序。

你的代码太长了,实际上很容易做到这一点

from datetime import datetime
test = {
'3001265': ['Samsung', 'phone', '1200', '12/1/2023', ''],
'1009453': ['Lenovo', 'tower', '599', '10/1/2020', ''],
'1167234': ['Apple', 'phone', '534', '2/1/2021', ''],
'2390112': ['Dell', 'laptop', '799', '7/2/2020', ''],
'9034210': ['Dell', 'tower', '345', '5/27/2020', ''],
'7346234': ['Lenovo', 'laptop', '239', '9/1/2020', 'damaged'],
'2347800': ['Apple', 'laptop', '999', '7/3/2020', '']
}
data = list(test.values())
result = sorted(data, key=lambda x:datetime.strptime(x[3], '%m/%d/%Y'))
print(result)

尝试更改此行:

sorted_entry = sorted(entry_list, key=lambda x: x[4])

收件人:

sorted_entry = sorted(entry_list, key=lambda x: datetime.strptime(x[4], '%m/%d/%Y'))

相关内容

  • 没有找到相关文章

最新更新