2011-04-29 180 views
15

我想獲得x出現在嵌套列表中的次數。嵌套列表和計數()

如果該列表是:

list = [1, 2, 1, 1, 4] 
list.count(1) 
>>3 

這是可行的。但是,如果列表是:

list = [[1, 2, 3],[1, 1, 1]] 

如何獲取1出現的次數?在這種情況下,4

+3

拼合第一。到處搜索。 – 2011-04-29 05:09:03

回答

9

這是另一種扁平化嵌套序列的方法。一旦順序變平,就可以輕鬆檢查項目的數量。

def flatten(seq,container=None): 
    if container is None: 
     container = [] 
    for s in seq: 
     if hasattr(s,'__iter__'): 
      flatten(s,container) 
     else: 
      container.append(s) 
    return container 


c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]]) 
print c 
print c.count('g') 

d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]]) 
print d 
print d.count(1) 

上面的代碼打印:

[1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 
1 
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 
12 
5

試試這個:

reduce(lambda x,y: x+y,list,[]).count(1) 

基本上,你開始與一個空列表[]並添加列表list的每個元素給它。在這種情況下,元素是列表本身,你會得到一個扁平列表。

PS:在另一個問題剛剛downvoted相似的答案!

PPS:剛剛爲此解決方案downvoted!

+0

這不適用於任意嵌套。 -1 – 2011-04-29 05:24:24

+5

人們在這裏任意投降。 Downvote for糟糕的解決方案。我的絕對不是。並沒有提到任意嵌套提及和OP的情況下工作。不要過度思考。 – manojlds 2011-04-29 05:34:27

+0

是的,因爲你拒絕進一步思考,並提供更深入的問題以及如何找到更一般的解決方案。 – 2011-04-29 05:46:28

8

itertoolscollections模塊僅獲得你需要(與itertools.chain展平嵌套列表,並與collections.Counter

import itertools, collections 

data = [[1,2,3],[1,1,1]] 
counter = collections.Counter(itertools.chain(*data)) 
print counter[1] 

計算使用遞歸扁平化的功能,而不是itertools.chain拉平任意級別的深度嵌套列表的東西

import operator, collections 

def flatten(lst): 
    return reduce(operator.iadd, (flatten(i) if isinstance(i, collections.Sequence) else [i] for i in lst)) 

reduceoperator.iadd已被用來代替sum,以便扁平物斯內德是建立只有一次,就地

+0

鏈()僅適用於1級嵌套壽命。 – 2011-04-29 05:19:43

+0

更新了答案 – Imran 2011-04-29 05:43:59

24
>>> L = [[1, 2, 3], [1, 1, 1]] 
>>> sum(x.count(1) for x in L) 
4 
+0

這不適用於任意嵌套。 - 1 – 2011-04-29 05:24:09

+13

@RestRisiko:問題說哪裏需要任意嵌套?你自己在這個問題上的答案甚至沒有涵蓋,但是你會爲其他人降低成績嗎? – 2011-04-29 05:25:22

+1

爲什麼人們低估了非常有效的答案。我給了這個+1,並且比我的回答更好。但我的回答並不糟糕,當然,這不是! – manojlds 2011-04-29 05:35:30

2

更新如果只有一個級別嵌套扁平化可以用這個列表comprenension來完成:

>>> L = [[1,2,3],[1,1,1]] 
>>> [ item for sublist in L for item in sublist ].count(1) 
4 
>>> 
4

爲它赫克:數到任何任意嵌套深度處理元組,列表和參數:

hits = lambda num, *n: ((1 if e == num else 0) 
    for a in n 
     for e in (hits(num, *a) if isinstance(a, (tuple, list)) else (a,))) 

lst = [[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]] 
print sum(hits(1, lst, 1, 1, 1)) 

15 
+1

爲這裏最酷的''lambda''濫用者+1 ;-)。這也回答瞭如何遞歸嵌入生成器本身的問題:-)。 – ThomasH 2011-04-29 08:41:44

0
def nested_count(lst, x): 
    return lst.count(x) + sum(
     nested_count(l,x) for l in lst if isinstance(l,list)) 

該函數返回occurr數量ences,加上所有包含的子列表中的遞歸嵌套計數。

>>> data = [[1,2,3],[1,1,[1,1]]] 
>>> print nested_count(data, 1) 
5