【发布时间】:2021-03-26 18:16:17
【问题描述】:
我正在尝试对数据列表进行排序,但似乎排序不起作用。我首先取出列表中的日期部分并尝试将其与当前日期进行比较。
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', '']
【问题讨论】: