Python 3: How to check lists within lists with .count()

老子叫甜甜 提交于 2019-12-23 05:42:06

问题


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???


回答1:


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')


来源:https://stackoverflow.com/questions/23299905/python-3-how-to-check-lists-within-lists-with-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!