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
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
根据您最近的评论,您似乎希望计算包含第一个列表元素的列表的数量。下面是一个小函数,它可以做到这一点:
现在,与casraf的答案类似,遍历}作为第一个参数,包含您感兴趣的所有其他列表的列表作为第二个参数:
^{pr2}$l1
,并调用函数count_in_lists()
,其中当前元素{这将为您提供以下输出:
您只需使用
in
运算符:如果要检查它是否在其他两个列表中的任何一个,只需将它们组合起来,然后在其中执行相同的检查:
^{pr2}$Demo
您可以使用设置交集函数,例如:
相关问题 更多 >
编程相关推荐