简体   繁体   English

如何检查元素是否是列表和整数列表的一部分?

[英]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.

相关问题 如何检查给定的整数列表是否是系列的一部分? - How to check if a given list of integers are part of the series? 如何检查列表列表中是否存在元素 - how to check if an element exists in a list of lists python 如何有效地检查元素是否在 python 的列表列表中 - How to efficiently check if an element is in a list of lists in python 如何检查一个元素是否存在于列表列表的 60% 中? - How to check if an element exists in 60% of the list of lists? 检查列表列表中是否存在元素 - Check if an element existed in a list of lists 如何检查异构列表中的元素(字典列表、内部列表) - How to check for an element in a heterogenous list ( list of dictionaries, inner lists) Python - 如何按每个列表中的第七个元素对带有整数和字符串的列表列表进行排序 - Python - How to sort a list of lists with integers and strings by the seventh element in each list 如何将字符串列表与整数列表列表相结合 - How to combine a string list with a list of lists of integers 使用子列表的元素的一部分对列表列表进行排序 - Sorting a list of lists, using part of an element of the sublists 如何遍历 2 个巨大的列表并查找列表 1 中的每个元素是否是列表 2 元素的一部分? - How to iterate through 2 huge lists and find if each element in list 1 is a part of an element of list 2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM