0

次のようなリストがあります。

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

私が言うなら

 if 2 in list1:
      print True

True を 1 回出力します。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) s 内の i の総出現回数

もちろん、内部では、countメソッドは全体を反復処理します(ただし、ループlistよりもはるかに高速です)。forパフォーマンス上の理由でそれを回避しようとしている場合、または の代わりに遅延反復子を使用できる場合は、list他のオプションを検討することをお勧めします。たとえばsort、リストと使用itertools.groupby、またはそれをにフィードしますcollections.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

collections.Counterこれにはオブジェクトを使用します。

from collections import Counter
myCounter = Counter(list1)

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

ただし、リストの1つまたはいくつかの要素でのみこれを行うことを計画している場合は、abarnert's answerを使用します。

于 2013-02-13T22:12:52.333 に答える
1
list1 = [1,2,4,6,8,9,2]
print list1.count(2)
于 2013-02-13T22:08:39.280 に答える
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 に答える
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 に答える