gpt4 book ai didi

python - 从列表中删除旧元素

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:31 24 4
gpt4 key购买 nike

我试图从包含 sub_list 的列表中删除类似的元素,其中包含元素的名称、日期和其他数据:

basket = [['奶酪', '2015/04/16', '垃圾'],['苹果', '2015/04/15', '其他垃圾'],['苹果' , '2015/03/15', '甜点'],['奶酪', '2017/04/16', '馅饼'],['香蕉', '2015/04/16', ''],[ '奶酪', '2017/04/10', '']]

如果元素名称(水果)在列表中出现两次,程序应比较日期并删除较旧的元素。我使用 datetime 来比较第二个元素,这部分正在工作。但是当我遍历列表时,它不断跳过 'banana'。这应该是最后添加的项目。

我尝试过这个方法:

def date_convert(date):
"""Takes a date string in the form YYYY/MM/DD and converts it to a
date object for comparisons."""

# Split date string by ".", " ", "/", or "-" to handle a wider range
# of possible inputs.
date = re.split('[. /\-]', date)

# Strip month of "0" because datetime does not accept that as valid
# input.
if(date[1][0] == '0'):
date[1] = date[1].strip('0')

return datetime.date(int(date[0]), int(date[1]), int(date[2]))




basket = [['cheese', '2015/04/16'],['apple', '2015/04/15'],['apple', '2015/03/15'],['cheese', '2017/04/16'],['banana', '2015/04/16'],['cheese', '2017/04/10']]

new_basket = []

for food in basket:
basket.remove(food)
for food2 in basket:
if food[0].upper() == food2[0].upper():
basket.remove(food2)

if date_convert(food[1]) > date_convert(food2[1]):
pass
else:
food = food2
else: new_basket.append(food)

print str(new_basket)

并收到此打印输出:[['cheese', '2017/04/16', 'pie'], ['apple', '2015/04/15', 'other junk']]

根据调试器的说法,它在 for 循环中永远不会到达banana。

最佳答案

这是一种选择。使用 defaultdict 按内部子列表的第一项进行分组。使用 max() 通过自定义 key 函数查找最大日期,这有助于将日期字符串与实际日期进行比较:

from collections import defaultdict
from datetime import datetime

basket = [['cheese', '2015/04/16', 'junk'],['apple', '2015/04/15', 'other junk'],['apple', '2015/03/15', 'dessert'],['cheese', '2017/04/16', 'pie'],['banana', '2015/04/16', ''],['cheese', '2017/04/10', '']]

d = defaultdict(list)
for item in basket:
d[item[0]].append(item[1:])

print([[key, max(values, key=lambda x: datetime.strptime(x[0], "%Y/%m/%d"))] for key, values in d.items()])

打印:

[['apple', ['2015/04/15', 'other junk']], ['banana', ['2015/04/16', '']], ['cheese', ['2017/04/16', 'pie']]]

请注意,在这种情况下您将失去订单。

关于python - 从列表中删除旧元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36553634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com