Python|检查列表列表中是否存在元素
给定一个列表列表,任务是确定给定元素是否存在于任何子列表中。下面给出了一些解决给定任务的方法。方法 #1:使用 any()
只要给定迭代器中存在特定元素, any()
方法就会返回 true。
# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = any(elem_to_find in sublist for sublist in ini_list)
res2 = any(elem_to_find1 in sublist for sublist in ini_list)
# printing result
print(str(res1), "\n", str(res2))
输出:
True
False
方法#2:使用运算符符
'in'运算符用于检查一个值是否存在于序列中。如果找到指定序列中的变量,则评估为true ,否则评估为false 。
# Python code to demonstrate
# finding whether element
# exists in listof list
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem = 8
elem1 = 0
# element exists in listof listor not?
res1 = elem in (item for sublist in ini_list for item in sublist)
res2 = elem1 in (item for sublist in ini_list for item in sublist)
# printing result
print(str(res1), "\n", str(res2))
输出:
True
False
方法 #3:使用itertools.chain()
创建一个迭代器,从第一个迭代器返回元素,直到它用尽,然后继续到下一个迭代器,直到所有的迭代器都用尽。
# Python code to demonstrate
# finding whether element
# exists in listof list
from itertools import chain
# initialising nested lists
ini_list = [[1, 2, 5, 10, 7],
[4, 3, 4, 3, 21],
[45, 65, 8, 8, 9, 9]]
elem_to_find = 8
elem_to_find1 = 0
# element exists in listof listor not?
res1 = elem_to_find in chain(*ini_list)
res2 = elem_to_find1 in chain(*ini_list)
# printing result
print(str(res1), "\n", str(res2))
输出:
True
False