问题描述
.count()不检查其他列表中的列表。我如何?
FirstList = [['1','2','3'],
[ '4','5','6'],
['7','8','9']]
While
FirstList [0] .count('1')
返回1.
我想检查所有FirstList。
这里有3种可能的解决方案:
给定:
xs = [['1','2' 3'],
['4','1','1'],
['7','8','1']]
[x .count('1')for x in xs]
将返回
[1,2,1]
如果要将其减少为单个值,请依次使用 sum
:
sum(x.count('1')for x in xs)
这将再次为您提供:
4
或者,您也可以平整嵌套列表,然后运行 count('1')
上一次:
a + b,xs).count('1')
b
$ b
4
正如JFSebastian指出的,这比简单的 sum
解决方案效率更低/更慢。
code> reduce ,您可以使用 itertools.chain
获得相同的效果(不增加计算复杂度):
list(chain(* xs))。count('1')
The .count() doesn't check lists within other lists. How can I?
FirstList = [ ['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'] ]
While
FirstList[0].count('1')
returns 1.I want to check all of FirstList. How can I do this???
Here are 3 possible solutions:
given:
xs = [['1', '2', '3'],
['4', '1', '1'],
['7', '8', '1']]
[x.count('1') for x in xs]
will return
[1, 2, 1]
and if you want to reduce that to a single value, use sum
on that in turn:
sum(x.count('1') for x in xs)
which will, again, give you:
4
or, alternatively, you can flatten the nested list and just run count('1')
on that once:
reduce(lambda a, b: a + b, xs).count('1')
which will yield
4
but as J.F.Sebastian pointed out, this is less efficient/slower than the simple sum
solution.
or instead of reduce
, you can use itertools.chain
for the same effect (without the added computational complexity):
list(chain(*xs)).count('1')
这篇关于Python 3:如何检查列表中列表与.count()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!