我想得到x出现在嵌套列表中的次数.
如果列表是:
list = [1, 2, 1, 1, 4]
list.count(1)
>>3
Run Code Online (Sandbox Code Playgroud)
还行吧.但如果列表是:
list = [[1, 2, 3],[1, 1, 1]]
Run Code Online (Sandbox Code Playgroud)
如何获得1次出现的次数?在这种情况下,4.
Tho*_*son 37
>>> L = [[1, 2, 3], [1, 1, 1]]
>>> sum(x.count(1) for x in L)
4
Run Code Online (Sandbox Code Playgroud)
Imr*_*ran 12
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]
Run Code Online (Sandbox Code Playgroud)
使用递归展平函数而不是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))
Run Code Online (Sandbox Code Playgroud)
reduce与operator.iadd已经使用,而不是sum使扁平内置只有一次,更新就地
sat*_*esh 12
这是另一种展平嵌套序列的方法.一旦序列变平,就可以轻松检查项目的数量.
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))
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
[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
Run Code Online (Sandbox Code Playgroud)
试试这个:
reduce(lambda x,y: x+y,list,[]).count(1)
Run Code Online (Sandbox Code Playgroud)
基本上,您从一个空列表开始,[]并将列表的每个元素添加list到它.在这种情况下,元素本身就是列表,你会得到一个扁平的列表.
PS:刚刚在另一个问题上得到了类似的答案!
PPS:刚刚推出这个解决方案!
| 归档时间: |
|
| 查看次数: |
32267 次 |
| 最近记录: |