0

我有一个看起来像这样的列表:

 list1 = [1,2,4,6,8,9,2]

如果我要说

 if 2 in list1:
      print True

它打印 True 一次。有没有办法确定 2 或任何变量 x 是否多次在列表中,如果有多少次而不像这样遍历整个列表?

for item in list1:
      if item = 2:
          duplicates +=1
4

6 回答 6

7

我想你正在寻找list.count

if list1.count(2) > 1:
    print True

序列类型中:

s.count(i) i 在 s 中出现的总次数

当然,在幕后,该count方法将遍历整个list(尽管它会比for循环快得多)。如果您出于性能原因试图避免这种情况,或者您可以使用惰性迭代器而不是 a list,您可能需要考虑其他选项。例如,sortlist 和 use itertools.groupby,或将其输入 acollections.Counter等。

于 2013-02-13T22:07:55.300 回答
4
from collections import Counter
y = Counter(list1)
print y[2]
print y[5] # and so on
于 2013-02-13T22:10:38.030 回答
1
list1 = [1,2,4,6,8,9,2]
print list1.count(2)
于 2013-02-13T22:08:39.280 回答
1

我会为此使用一个collections.Counter对象:

from collections import Counter
myCounter = Counter(list1)

print myCounter[2] > 1 #prints 'True'

但是,如果您只打算对列表中的一个或几个元素执行此操作,我会选择abarnert 的答案

于 2013-02-13T22:12:52.333 回答
0

Collections.counter (正如其他人所指出的)是我将如何做到这一点。但是,如果你真的想弄脏你的手:

def count(L):
    answer = {}
    for elem in L:
        if elem not in answer:
            answer[elem] = 0
        answer[elem] += 1
    return answer

>>> counts = count(myList)
>>> duplicates = [k for k,v in counts.iteritems() if v>1]
于 2013-02-13T22:16:11.203 回答
0
list1 = [1,2,4,6,8,9,2]

dict1 = {}

for ele in list1:
    # you iterate through the list once
    if ele in dict1:
        # if a key is already in the dictionary
        # you increase the corresponding value by one
        dict1[ele] += 1 
    else:
        # if a key is not yet in the dictionary
        # you set its corresponding value to one
        dict1[ele] = 1

结果:

>>> dict1
{1: 1, 2: 2, 4: 1, 6: 1, 8: 1, 9: 1}
于 2013-02-13T22:26:02.597 回答