0

这是我所知道的,不知道我是否正确地做。

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

4 回答 4

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")

于 2012-10-16T21:23:30.713 回答
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)Lix4

于 2012-10-16T21:11:48.730 回答
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)然后你可以用它做同样的事情..

于 2012-10-16T21:16:16.760 回答
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]
于 2012-10-16T21:18:51.407 回答