在列表中选择最早的条目 [英] selecting the earliest entry in a list

查看:72
本文介绍了在列表中选择最早的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含人名和日期的列表,而我只想保留每个人最早的日期,该怎么办?我希望最终列表按姓氏字母顺序,然后按名字,并且仅包含末尾最早日期的条目.

If I have a list with people's names and dates, and I want only to keep the entry for the earliest date per person how do I do that? I want the final list to be alphabetical by last name, then first name and only contain the entry with the earliest date at the end.

这是列表的示例和我尝试过的方法,但它又给了我相同的列表.

Here is an example of the list and what I tried, but it just gave me back the same list again.

L1=['Smith, John, 1994', 'Smith, John, 1996', 'Smith, John, 1998', 'Smith, Joan, 1993', 'Smith, Joan, 1995', 'Smith, Jack, 1989', 'Smith, Jack, 1991', 'Jones, Adam, 2000', 'Jones, Adam, 1998', 'Jones, Sarah, 2002', 'Jones, Sarah, 2005', 'Brady, Tom, 2001', 'Brady, Tonya, 2002']

L1.sort()

L2= []

for item in L1:
    if item.split(',')[:2] not in L2:
        L2.append(item)

最终产品应如下所示:

L2=['Brady, Tom, 2001', 'Brady, Tonya, 2002', 'Jones, Adam, 1998', 'Jones, Sarah, 2002', 'Smith, Jack, 1989', 'Smith, Joan, 1993', 'Smith, John, 1994']

任何帮助或见识将不胜感激!

Any help or insight would be greatly appreciated!

推荐答案

尝试

L1.sort()
[next(j) for i, j in itertools.groupby(L1, lambda x: x.rsplit(",", 1)[0])]

您的代码不起作用,因为您正在L2中搜索item.split(',')[:2],这只是名称.但是列表中的字符串由名称和年份组成-这就是not in总是产生True的原因.

Your code does not work since you are searching L2 for item.split(',')[:2], which is only the name. But the strings in the list consist of the name and the year -- that's why the not in always yields True.

这篇关于在列表中选择最早的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆