【问题标题】:How to merge duplicates in two lists of strings?如何合并两个字符串列表中的重复项?
【发布时间】:2017-07-08 21:50:16
【问题描述】:

我对 python (2.7) 有点陌生,我很难做到这一点。

我有以下列表:

animal = ['cat', 'cat', 'dog', 'dog', 'dog', 'horse']
names = ['cat_01', 'cat_02', 'dog_01', 'dog_02', 'dog_03', 'horse_01']

我想要以下内容(可以是元组列表或字典)

new = {"cat":('cat_01','cat_02'), "dog":('dog_01','dog_02', 'dog_03'), "horse":('horse_01')}

如何最好地做到这一点?

【问题讨论】:

    标签: python python-2.7 list dictionary duplicates


    【解决方案1】:

    使用列表理解的简短解决方案:

    animal = ['cat', 'cat', 'dog', 'dog', 'dog', 'horse']
    names = ['cat_01', 'cat_02', 'dog_01', 'dog_02', 'dog_03', 'horse_01']
    result = {a:tuple([n for n in names if a in n]) for a in animal}
    
    print result
    

    输出:

    {'cat': ('cat_01', 'cat_02'), 'horse': ('horse_01',), 'dog': ('dog_01', 'dog_02', 'dog_03')}
    

    【讨论】:

    • 这可以为in 运算符更改str.startwith。因为我正在处理不以我需要的字符串开头的文件路径。还是谢谢你!
    【解决方案2】:

    您也可以从itertools 使用groupby

    from itertools import groupby
    my_dict = {}
    for key, groups in groupby(zip(animal, names), lambda x: x[0]):
        my_dict[key] = tuple(g[1] for g in groups)
    

    当您的列表增加时,这可能会快一点。

    【讨论】:

      【解决方案3】:

      假设您的列表按照示例中的方式排序:

      代码:

      my_dict = {}
      for animal, name in zip(animals, names):
          my_dict.setdefault(animal, []).append(name)
      print(my_dict)
      

      给予:

      {'horse': ['horse_01'], 'dog': ['dog_01', 'dog_02', 'dog_03'], 'cat': ['cat_01', 'cat_02']}
      

      如果您需要元组而不是列表:

      my_dict = {k: tuple(v) for k, v in my_dict.items()}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-11
        • 1970-01-01
        • 2017-06-05
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-29
        • 2023-03-24
        相关资源
        最近更新 更多