[英]How to check if an element is part of a list of lists and integers?
I need to check if an element is part of a list, but the list looks like: 我需要检查元素是否属于列表,但是列表看起来像:
>>> lst = [[1,2], 3, [1,2], [1,4]]
>>> possible = [1,4]
I tried to check it with multiple for-loops, but the problem is the integer, it isn't iterable. 我试图用多个for循环检查它,但是问题是整数,它不是可迭代的。
>>> for pos_elem in range(len(possible)):
for i in lst:
for j in i:
if possible[pos_elem] == j:
print j
Is there a code that will check every element of lst without error? 是否有代码可以检查lst的每个元素而不会出错?
if possible in lst:
#do something
Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. Python具有成员资格运算符,可测试序列中的成员资格,例如字符串,列表或元组。 There are two membership operators.
有两个成员运算符。
in
and not in
in
not in
in
Evaluates to true if it finds a variable in the specified sequence and false otherwise. in
评估为TRUE,如果它发现了指定的顺序,否则为假在变量中。 not in
Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. not in
如果找不到指定序列中的变量,则评估为true,否则为false。 You could use python's built in type
to check if the element in the list is a list or not like so: 您可以使用python的内置
type
来检查列表中的元素是否为列表,如下所示:
lst = [[1, 2], 3, [1, 2], [1, 4]]
possible = [1, 4]
for element in lst:
#checks if the type of element is list
if type(element) == list:
for x in element:
if x in possible:
print x
else:
if element in possible:
print element
Prints: 打印:
1
1
1
4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.