将一个列表中的单词与其他列表中的单词进行比较

2024-05-23 14:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我该如何检查一个列表中的一个单词是否等于另一个列表中的单词?
例如,我有三个列表:

["fish", "boat", "oar"], ["rod", "gunwale", "fish", "net"], ["net", "hook", "weight"] 

如何检查第一个列表中的单词是否出现在其他列表中?例如,我如何迭代其他两个列表中的每一个单词,看它们中是否有“fish”这个词,而“boat”和“oar”也是如此


Tags: 列表nethook单词weightfishoarrod
3条回答

根据您最近的评论,您似乎希望计算包含第一个列表元素的列表的数量。下面是一个小函数,它可以做到这一点:

def count_in_lists(e, lol):
    """
    Count how many of the lists passed in the list of lists 'lol' contain
    the element 'e'.
    """
    count = 0
    for current_list in lol:
        if e in current_list:
            count += 1
    return count

现在,与casraf的答案类似,遍历l1,并调用函数count_in_lists(),其中当前元素{}作为第一个参数,包含您感兴趣的所有其他列表的列表作为第二个参数:

^{pr2}$

这将为您提供以下输出:

'fish' is contained in 1 other lists
'boat' is contained in 0 other lists
'oar' is contained in 0 other lists

您只需使用in运算符:

l1 = ["fish", "boat", "oar"]
l2 = ["rod", "gunwale", "fish", "net"]
l3 = ["net", "hook", "weight"] 

for w in l1:
  if w in l2:
    print 'found %s in l2!' % w
  if w in l3:
    print 'found %s in l3!' % w

如果要检查它是否在其他两个列表中的任何一个,只需将它们组合起来,然后在其中执行相同的检查:

^{pr2}$

Demo

您可以使用设置交集函数,例如:

s1 = set(["fish", "boat", "oar"]) 
s2 = set(["rod", "gunwale", "fish", "net"])
s3 = set(["net", "hook", "weight"])
commonS12 = s1 & s2#gives you common elements

相关问题 更多 >