我想得到x在嵌套列表中出现的次数。
如果列表是:
list = [1, 2, 1, 1, 4]
list.count(1)
>>3
这样就可以了。但如果列表是:
list = [[1, 2, 3],[1, 1, 1]]
如何获取1出现的次数?在本例中,为4。
发布于 2011-04-29 14:51:54
这是另一种扁平化嵌套序列的方法。一旦序列被展平,就可以很容易地检查项目的数量。
def flatten(seq, container=None):
if container is None:
container = []
for s in seq:
try:
iter(s) # check if it's iterable
except TypeError:
container.append(s)
else:
flatten(s, container)
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
发布于 2011-04-29 13:13:29
>>> L = [[1, 2, 3], [1, 1, 1]]
>>> sum(x.count(1) for x in L)
4
发布于 2011-04-29 13:11:43
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))
已使用带有operator.iadd
的reduce
代替sum
,以便只构建一次展平并就地更新
https://stackoverflow.com/questions/5828123
复制相似问题