2012-10-16 29 views
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] 

回答

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,並從它們構建一個列表。無需查看列表的長度。

+0

所以我不必使用列表的長度? – neonlights

+0

值得注意的是,要顯示所有元素的這些信息,你可以遍歷'set(L)''(避免多次顯示每個項目,因爲集合不存儲重複項)。 –

+0

@neonlights你爲什麼? –

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),然後你可以做同樣的吧..

+0

不要使用'is'進行平等比較! –

+0

@TimPietzcker好的。編輯的代碼。 :) –

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