【问题标题】:Compare unique string values between two lists and get the count of matched values in python比较两个列表之间的唯一字符串值并获取python中匹配值的计数
【发布时间】:2019-03-09 23:54:24
【问题描述】:

我有两个列表,其中一些项目是共同的,有些则不是。我想比较这两个列表并获取匹配项的数量。

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

请告知如何在 python 中执行此操作

【问题讨论】:

    标签: python-3.x list string-comparison


    【解决方案1】:

    我认为你可以在这个例子的理解中使用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}
    

    【讨论】:

      【解决方案2】:

      使用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
      

      【讨论】:

      • 谢谢。我将在我的代码中对此进行测试并返回
      • 如果我有多个这样的列表并且我只想一次比较一对列表,请您提出建议。例如:仅 List1 和 List2,然后仅 List3 和 List4。假设数据框中的列表在一列中显示 List1 和 List3,在旁边的列中显示 List2 和 List4。
      • 如果没有合适的数据示例,很难回答这个问题。听起来你会想要循环遍历这些对。
      • df = pd.DataFrame({ 'Col1':[['Phone', 'Watch', 'Pen', 'Pencil', 'Knife'],['apple','orange' ,'mango','cherry','banana','kiwi','tomato','avocado']], 'Col2': [['Phone', 'Watch', 'Pen', 'Pencil', '叉子'],['橙子','鳄梨','猕猴桃','芒果','葡萄','柠檬','番茄']]})
      • 我已经给出了一个示例 df 代码。您会注意到第一行中的列只值得比较,同样可以比较第二行中的列。我也想这样做。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      相关资源
      最近更新 更多