【问题标题】:Remove older elements from a list从列表中删除旧元素
【发布时间】: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


【解决方案1】:

这是一种选择。使用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']]]

请注意,在这种情况下您会丢失订单。

【讨论】:

  • 谢谢,这正是我所需要的,但有一个小问题。每个子列表在日期之后都有其他条目(更新了问题)。我似乎无法将这些包含在排序中。
  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 2014-12-19
  • 2013-11-25
相关资源
最近更新 更多