如何让程序打印列表中出现数字的次数?

时间:2012-10-16 21:08:32

标签: python list element

这就像我知道怎么做,不确定我是否正确地做到了。

L = [4, 10, 4, 2, 9, 5, 4 ]

n = len(L)
element = ()


if element in L:
    print(element)

print("number occurs in list at the following position, if element not in list")
print("this number does not occur in the list")

如何获取多次出现的元素,以

打印
4 occurs in L at the following positions:  [0, 2, 6]

4 个答案:

答案 0 :(得分:2)

强制defaultdict帖子:

from collections import defaultdict

el = [4, 10, 4, 2, 9, 5, 4 ]
dd = defaultdict(list)
for idx, val in enumerate(el):
    dd[val].append(idx)

for key, val in dd.iteritems():
    print '{} occurs in el at the following positions {}'.format(key, val)

#9 occurs in el at the following positions [4]
#10 occurs in el at the following positions [1]
#4 occurs in el at the following positions [0, 2, 6]
#2 occurs in el at the following positions [3]
#5 occurs in el at the following positions [5]

然后dd只能用于普通字典...... dd[4]dd.get(99, "didn't appear")

答案 1 :(得分:1)

您可以使用列表理解:

>>> L = [4, 10, 4, 2, 9, 5, 4]
>>> [i for i,x in enumerate(L) if x==4]
[0, 2, 6]

enumerate(L)L提供了一个迭代器,为(index, value)的每个元素生成一个元组L。所以我在这里做的是,如果值(i)等于x,则获取每个索引(4),并从中构造一个列表。无需查看列表的长度。

答案 2 :(得分:0)

您可以使用Counter计算列表中的不同元素,然后使用列表推导来查找每个元素的索引: -

>>> l = [4, 10, 4, 2, 9, 5, 4 ]
>>> from collections import Counter
>>> count = Counter(l)
>>> count
Counter({4: 3, 9: 1, 10: 1, 2: 1, 5: 1})

>>> lNew = [[(i,x) for i,x in enumerate(l) if x == cnt]  for cnt in count]
>>> 
>>> lNew[0]
[(4, 9)]
>>> lNew[1]
[(1, 10)]
>>> lNew[2]
[(0, 4), (2, 4), (6, 4)]
>>>  

实际上你在这里不需要Counter。您可以使用Set

下车

使用工厂函数创建一个列表集: - set(l)然后你可以用它做同样的事情..

答案 3 :(得分:0)

def print_repeated_elements_positions(L):
    for e in set(L): # only cover distinct elements
        if L.count(e) > 1: #only those which appear more than once
            print(e, "occurs at", [i for i, e2 in enumerate(L) if e2 == e])


L = [4, 10, 4, 2, 9, 5, 4]
print_repeated_elements_positions(L)
# prints: 4 occurs at [0, 2, 6]