代码之家  ›  专栏  ›  技术社区  ›  Sudhi

比较两个列表之间的唯一字符串值,并在python中获得匹配值的计数

  •  0
  • Sudhi  · 技术社区  · 6 年前

    list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
    list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
    

    请建议如何在python中这样做

    2 回复  |  直到 6 年前
        1
  •  1
  •   PyPingu    6 年前

    使用 Counters

    list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
    list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
    c1 = Counter(list1)
    c2 = Counter(list2)
    matching = {k: c1[k]+c2[k] for k in c1.keys() if k in c2}
    print(matching)
    print('{} items were in both lists'.format(len(macthing))
    

    输出:

    {'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2, 'kiwi': 2}
    5 items were in both lists
    
        2
  •  1
  •   Chiheb Nexus    6 年前

    我想你可以用 set.intersection 在这样一个例子中:

    list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
    list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
    
    result = {elm: list1.count(elm) + list2.count(elm) for elm in set.intersection(set(list1), set(list2))}
    

    {'kiwi': 2, 'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2}