简体   繁体   English

列表列表中的元组中count元素=“”

[英]count elements = “” in tuples inside a list of lists

I have a list of lists of tuples: 我有一个元组列表的列表:

[[("AA","AA"),("QQ","")],[("CC",""),("QQ","")],...]

I am trying to count the number of empty values "" in the second value of the tuples. 我试图在元组的第二个值中计算空值""的数量。 In the case above it would be: 在上述情况下,它将是:

I needed the answer in a list with the sum of occurrences for each nested list (in the example above it would be [1,2,...]. 我需要一个列表中的答案,其中包含每个嵌套列表的出现总数(在上面的示例中为[1,2,...]。

I was trying something like that 我在尝试类似的东西

with open(file, 'r') as f:
    obj = pickle.load(f)
    count=Counter(elem for elem in el for el in obj if elem[0]=="")

Is it possible to somehow use 2 "for" for nested lists? 是否有可能以2个“ for”用于嵌套列表?

Use a list comprehension with sum() and a generator expression: 使用带有sum()和生成器表达式的列表推导:

[sum(1 for t in tups if t[1] == '') for tups in obj]

Demo: 演示:

>>> obj = [[("AA", "AA"), ("QQ", "")], [("CC", ""), ("QQ", "")]]
>>> [sum(1 for t in tups if t[1] == '') for tups in obj]
[1, 2]
[sum(0 if x[1] else 1 for x in sub_lst) for sub_lst in big_list]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM