[英]How Can I count the number of occurences for two items in a nested list
I have a nested list我有一个嵌套列表
a = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
how can i count the number of occurrences that a & b appeared in the nested list?如何计算 a & b 在嵌套列表中出现的次数?
in this case the answer shall be 2 times.在这种情况下,答案应为 2 次。
ps this is my first time post, so thanks for all the help. ps 这是我第一次发帖,谢谢大家的帮助。
You can test for inclusion in a list with您可以测试是否包含在列表中
'a' in some_list
This will be true or false.这将是真的或假的。 You can make multiple tests with
and
(there are also some other ways that may be a little prettied):您可以使用
and
进行多个测试(还有一些其他方法可能会有点漂亮):
'a' in some_list and 'b' in some_list
This will be true if both conditions are met.如果这两个条件都满足,这将是正确的。 To do this for all the lists in your list you can use a list comprehension:
要对列表中的所有列表执行此操作,您可以使用列表理解:
a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
['a' in x and 'b' in x for x in a_list]
This will return a list of boolean values, one for each item in your list:这将返回一个布尔值列表,列表中的每个项目一个:
[True, False, True]
When treated like numbers python treats True
as 1
and False
as 0
.当像数字一样对待时,python 将
True
视为1
,将False
视为0
。 This means you can just sum that list to get you count and have a solution in one line:这意味着您可以对该列表进行求和,以计算并在一行中找到解决方案:
a_list = [[1,'a','b'], [2,'c','d'], [3,'a','b']]
sum(['a' in x and 'b' in x for x in a_list])
# 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.