【问题标题】:count occurrences of list items in second list in python计算python中第二个列表中列表项的出现次数
【发布时间】:2019-04-23 11:06:49
【问题描述】:
a = list([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
b = list([1, 3, 6, 9])

如何计算列表中的项目在列表a中出现的次数?

上面的例子应该返回一个值 4。

在写这个问题时,我想到了以下(似乎可行)

a = list([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
b = list([1, 3, 6, 9])
c = 0
for n in b:
    if n in a:
        c += 1
        continue
print (c)

但是必须有一种更简洁的方式使用列表比较或其他东西?

【问题讨论】:

  • b 是否保证是唯一值?正如你可以做的那样len(set(b).intersection(a))...
  • 您无需在所有列表中都打上list 电话。
  • 您要计算特定项目的出现次数吗?例如1 在列表 a 中出现的频率。或者你想计算两个列表有多少相同的项目?
  • @Jon Clements - 在这种情况下,两个列表都是独一无二的。
  • @user2357112 - 谢谢,我是 py 新手

标签: python python-3.x list python-3.6


【解决方案1】:

你可以使用内置的sum:

sum(i in b for i in a)

输出:

4

【讨论】:

  • 为什么这被否决了?到目前为止,还不可能确切地知道 OP 拥有的数据
【解决方案2】:

如果您只想计算两个列表中的元素数量(并且您不需要知道它们在另一个列表中出现了多少次),您可以使用:

count = len(set(a).intersection(set(b)))

或相同:

count = len(set(a) & set(b))

【讨论】:

    【解决方案3】:

    使用set的简单方法:

    >>> len(set(a) & set(b))
    4
    

    这是一个老问题,看看: How can I compare two lists in python and return matches

    【讨论】:

    • 这个问题和你链接的问题的区别是我不想返回匹配的值,我只需要计算有多少。
    • 是的,当然。我只说比较列表(在你能数与否之后)是一个老问题:) 我希望我能帮助你。
    • 谢谢。我对 py 很陌生,有时我很难找出相关代码,因为很多示例通常做的事情与我想做的事情不同。
    • 好的,我已经接受了你的回答和上面@Chris 的回答作为我问题的解决方案。我将两个都付钱,看看哪个最适合我。谢谢。
    • 这和我的回答一模一样。
    【解决方案4】:

    在一行中试试这个:

    s = sum(a.count(i) for i in b if i in a)
    

    s 将是 4 作为输出。 此外,它还支持a中的重复项。

    【讨论】:

    • 这是不必要的低效,因为您在每次迭代中计算相同的计数。
    【解决方案5】:

    以下是一些计算重复项并忽略所有不在 b 中的值的变体。

    from collections import Counter
    # a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    a = [1, 4, 3, 1, 2, 4, 4, 5, 6, 6, 7, 7, 7, 7, 8, 9, 0, 1]
    b = [1, 3, 6, 9]
    
    counts = Counter()
    # make counts order match b order
    for item in b:
        counts[item] = 0
    for item in a:
        if item in b:
            counts[item] += 1
    print("in 'b' order")
    print([(k, v) for k, v in counts.items()])
    print("in descending frequency order")
    print(counts.most_common())
    print("count all occurrences in a of elements that are also in b")
    print(sum(counts.values()))
    
    
    
    python count_b_in_a.py
    in 'b' order
    [(1, 3), (3, 1), (6, 2), (9, 1)]
    in descending frequency order
    [(1, 3), (6, 2), (3, 1), (9, 1)]
    count all occurrences in a of elements that are also in b
    7
    

    针对您对性能的评论,下面是扫描列表和扫描集合在 Python 中的比较:

    import datetime
    
    def timestamp():
        return datetime.datetime.now()
    
    
    def time_since(t):
        return (timestamp() - t).microseconds // 1000
    
    
    a = list(range(1000_000))
    b = set(a)
    iterations = 10
    t = timestamp()
    for i in range(iterations):
        c = 974_152 in a
    print("Finished {iterations} iterations of list scan in {duration}ms"
          .format(iterations=iterations, duration=time_since(t)))
    t = timestamp()
    for i in range(iterations):
        c = 974_152 in b
    print("Finished {iterations} iterations of set scan in {duration}ms"
          .format(iterations=iterations, duration=time_since(t)))
    
    python scan.py
    Finished 10 iterations of list scan in 248ms
    Finished 10 iterations of set scan in 0ms
    

    要注意的第一点:Python 也毫不逊色。在一台旧笔记本电脑上 1/4 秒扫描 1000 万个列表元素还不错。但它仍然是线性扫描。

    Python 集属于不同的类。如果您从time_since() 中取出// 1000,您会看到Python 在不到一微秒的时间内扫描了100 万个成员集10 次。您会发现其他集合操作也快如闪电。无论集合在 Python 中适用于何处,都可以使用它们:它们太棒了。

    如果您打算将上述代码应用到更大的列表中,其中性能很重要,首先要做的可能是将b 转换为集合。

    【讨论】:

    • 谢谢,但是代码比我用的多很多,效率更高吗?
    • 代码更多,因为它为您提供了更多选择。 Counter 很快。如果您只对a 中的每个项目是否存在感兴趣,则set() 操作是最快的。这是 Python,如果你想要超级高效,你就来错地方了。坦率地说,我发现 Python 很少有效率问题。总体而言,Python 文化对清晰、简单、可维护的代码比顶级性能更感兴趣。
    • 很公平。感谢您的回复。
    【解决方案6】:

    这个单线应该也可以。找出每个元素的计数并将这些计数相加

    op = sum([a.count(j) for j in b])
    

    输出将是

    a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    b = [1, 3, 6, 9]
    #4
    a = [1, 1, 2, 3, 3, 3, 4, 5, 6, 6 , 7, 8, 9, 0]
    b = [1, 3, 6, 9]
    #8
    
    

    【讨论】:

    • 这似乎与上面@Mehrdad Pedramfar 的回答相似,后者被指控效率低下。不过,如果是这样的话,我还不足以发表评论。
    【解决方案7】:

    虽然集合适用于独特

    列表理解也考虑重复项

    a = [1,1]
    b = [1,1]
    
    count = len(set(a) & set(b)) 
    count2 = sum(i in b for i in a)  
    print(count, count2) 
    
    1 2
    
    [Program finished] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      相关资源
      最近更新 更多