我想获得x出现在嵌套列表中的次数。嵌套列表和计数()
如果该列表是:
list = [1, 2, 1, 1, 4]
list.count(1)
>>3
这是可行的。但是,如果列表是:
list = [[1, 2, 3],[1, 1, 1]]
如何获取1出现的次数?在这种情况下,4
我想获得x出现在嵌套列表中的次数。嵌套列表和计数()
如果该列表是:
list = [1, 2, 1, 1, 4]
list.count(1)
>>3
这是可行的。但是,如果列表是:
list = [[1, 2, 3],[1, 1, 1]]
如何获取1出现的次数?在这种情况下,4
这是另一种扁平化嵌套序列的方法。一旦顺序变平,就可以轻松检查项目的数量。
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
试试这个:
reduce(lambda x,y: x+y,list,[]).count(1)
基本上,你开始与一个空列表[]
并添加列表list
的每个元素给它。在这种情况下,元素是列表本身,你会得到一个扁平列表。
PS:在另一个问题刚刚downvoted相似的答案!
PPS:刚刚为此解决方案downvoted!
这不适用于任意嵌套。 -1 – 2011-04-29 05:24:24
人们在这里任意投降。 Downvote for糟糕的解决方案。我的绝对不是。并没有提到任意嵌套提及和OP的情况下工作。不要过度思考。 – manojlds 2011-04-29 05:34:27
是的,因为你拒绝进一步思考,并提供更深入的问题以及如何找到更一般的解决方案。 – 2011-04-29 05:46:28
itertools
和collections
模块仅获得你需要(与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))
reduce
与operator.iadd
已被用来代替sum
,以便扁平物斯内德是建立只有一次,就地
链()仅适用于1级嵌套寿命。 – 2011-04-29 05:19:43
更新了答案 – Imran 2011-04-29 05:43:59
>>> L = [[1, 2, 3], [1, 1, 1]]
>>> sum(x.count(1) for x in L)
4
这不适用于任意嵌套。 - 1 – 2011-04-29 05:24:09
@RestRisiko:问题说哪里需要任意嵌套?你自己在这个问题上的答案甚至没有涵盖,但是你会为其他人降低成绩吗? – 2011-04-29 05:25:22
为什么人们低估了非常有效的答案。我给了这个+1,并且比我的回答更好。但我的回答并不糟糕,当然,这不是! – manojlds 2011-04-29 05:35:30
更新如果只有一个级别嵌套扁平化可以用这个列表comprenension来完成:
>>> L = [[1,2,3],[1,1,1]]
>>> [ item for sublist in L for item in sublist ].count(1)
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
为这里最酷的''lambda''滥用者+1 ;-)。这也回答了如何递归嵌入生成器本身的问题:-)。 – ThomasH 2011-04-29 08:41:44
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
拼合第一。到处搜索。 – 2011-04-29 05:09:03