【发布时间】:2016-08-01 21:45:41
【问题描述】:
我正在尝试从包含包含元素名称、日期和其他数据的 sub_list 的列表中删除类似元素:
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', '']]
如果一个元素名称(fruit)在列表中出现两次,程序应该比较日期并删除旧元素。我正在使用 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 循环中到达香蕉。
【问题讨论】:
-
输出列表中的顺序重要吗?谢谢。
-
对于方法?可能。但根本不是所需的输出。
标签: python list python-2.7 for-loop iteration