【问题标题】:Find and Remove duplicates from list while concatenating second list在连接第二个列表时从列表中查找和删除重复项
【发布时间】:2019-02-02 20:56:26
【问题描述】:

我有两个列表,第一个列表包含重复值。 我需要从List1 中删除重复项,并将List2 中的值合并到与List1 重复值相同的索引上。

我有什么:

List1 = ['show1', 'show2', 'show3', 'show2', 'show4', 'show4']
List2 = ['1pm', '10am', '11pm', '2pm', '5pm', '3pm']

我需要什么:

List1 = ['show1', 'show2', 'show3', 'show4']
List2 = ['1pm', '10am | 2pm', '11pm', '5pm | 3pm']

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    假设你使用的是 Python 3.7+,你可以试试这个:

    from collections import defaultdict
    
    List1 = ['show1', 'show2', 'show3', 'show2', 'show4', 'show4']
    List2 = ['1pm', '10am', '11pm', '2pm', '5pm', '3pm']
    
    d = defaultdict(list)
    
    for show, time in zip(List1, List2):
        d[show].append(time)
    
    List1 = list(d.keys())
    List2 = [' | '.join(times) for times in d.values()]
    print(List1)
    print(List2)
    

    输出:

    ['show1', 'show2', 'show3', 'show4']
    ['1pm', '10am | 2pm', '11pm', '5pm | 3pm']
    

    对于低于 3.7 的版本,您可以将最后几行替换为以下内容(工作量稍大):

    List1 = []
    List2 = []
    
    for show, times in d.items():
        List1.append(show)
        List2.append(' | '.join(times))
    

    【讨论】:

    • 您应该注意List1 的顺序在许多 Python 版本中是不保证的(3.6 之前,3.6 用于任何非 CPython)。
    • 添加到 @RoryDaulton 所说的关于 defaultdict.keys() 不保留 3.6 之前 Python 版本的排序顺序的内容,这里讨论了这个问题:stackoverflow.com/questions/31770251/…
    • @RoryDaulton - 为清楚起见,我假设您指的是List1 的顺序,它被变异为defaultdict 键的列表(不是第一个初始化列表的顺序)。
    • @benvc 正确,此答案不会保留 List1 中项目的原始顺序,因为 defaultdict.keys() 不保证 3.6 之前的 Python 版本中的顺序(正如 @RoryDaulton 指出的那样)。
    • @RoryDaulton 我添加了一个对版本更友好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多