检查一个单词在元组列表中是否至少出现两次?

时间:2019-05-12 18:35:22

标签: python list

假设我有一个列表:

[('a','Organization'),('b','Organization'),('c','Person'),('d','Location'),('e','Organization')]

我怎么知道单词'Organization'在此列表中是否至少出现了两次?

我还获得了另一个解决方案:

Counter([c for (w,c) in list])['ORGANIZATION'] >= 2

5 个答案:

答案 0 :(得分:3)

您可以使用生成器理解和sum来计算'Organization'出现的次数:

l = [('a','Organization'),('b','Organization'),
     ('c','Person'),('d','Location'),('e','Organization')]

sum(1 for i,j in l if j == 'Organization') > 2
# True

答案 1 :(得分:1)

尝试一下:

Counter({1: 2488, 2: 1907, 3: 1386, 4: 1084, 5: 786, 6: 623, 7: 464, 8: 322, 9: 262, 10: 164, 11: 127, 12: 100, 13: 66, 14: 61, 15: 48, 16: 26, 17: 24, 18: 12, 22: 9, 19: 8, 21: 8, 20: 7, 26: 3, 23: 3, 24: 3, 28: 2, 25: 2, 27: 2, 33: 1, 31: 1, 35: 1})

输出

a = [('a','Organization'),('b','Organization'),('c','Person'),('d','Location'),('e','Organization')]
check_tot_appearance = sum(1 for i in a if 'Organization' in i)>=2

答案 2 :(得分:1)

list = [('a','Organization'),('b','Organization'),('c','Person'),('d','Location'),('e','Organization')]

sublist = [value[1] for value in list]  # retrieve every second value of each tuple
print(sublist.count('Organization'))  # find occurrences of 'Organization'

答案 3 :(得分:1)

使用operator.itemgetter

的另一种方法

例如:

from operator import itemgetter
data = [('a','Organization'),('b','Organization'),('c','Person'),('d','Location'),('e','Organization')]

print(list(map(itemgetter(1), data)).count("Organization"))

输出:

3

答案 4 :(得分:0)

使用filter检查元组中的“组织”,如果计数长度大于两倍,则返回True

a=[('a','Organization'),('b','Organization'),('c','Person'),('d','Location'),('e','Organization')]

print(len(list(filter(lambda x: 'Organization' in x,a)))>=2 )

#output True