How to use the Python 'in' operator to verify that my list / tuple contains each of the integers 0, 1, 2?

How to use the Python in operator to verify that my sltn list / tuple contains each of the integers 0, 1, and 2?

I tried the following why they are both wrong:

 # Approach 1 if ("0","1","2") in sltn: kwd1 = True # Approach 2 if any(item in sltn for item in ("0", "1", "2")): kwd1 = True 

Update: why did I have to convert ("0", "1", "2") to any tuple (1, 2, 3) ? or the list [1, 2, 3] ?

+6
source share
4 answers
 if ("0","1","2") in sltn 

You are trying to check if the sltn list sltn tuple ("0","1","2") that is not there. (It contains 3 integers)

But you can do this using # all () :

 sltn = [1, 2, 3] # list tab = ("1", "2", "3") # tuple print(all(int(el) in sltn for el in tab)) # True 
+8
source

Using the in keyword is a shorthand for calling the __contains__ object __contains__ .

 >>> a = [1, 2, 3] >>> 2 in a True >>> a.__contains__(2) True 

Thus, ("0","1","2") in [0, 1, 2] asks if the tuple ("0", "1", "2") in the list [0, 1, 2] . The answer to this question is False . To be True , you will need to have a list like this:

 >>> a = [1, 2, 3, ("0","1","2")] >>> ("0","1","2") in a True 

Also note that the elements of your tuple are strings. You will probably want to check if any or all elements of your tuple are in your list after converting these elements to integers.

To check if all tuple elements (as integers) are contained in the list, use

 >>> sltn = [1, 2, 3] >>> t = ("0", "2", "3") >>> set(map(int, t)).issubset(sltn) False 

To check if any element of the tuple (as a whole) is contained in the list, you can use

 >>> sltn_set = set(sltn) >>> any(int(x) in sltn_set for x in t) True 

and use a lazy rating of any .

Of course, if your tuple contains strings for no particular reason, just use (1, 2, 3) and omit the conversion to int.

+22
source

To check if your sequence contains all the elements you want to check, you can use the generator understanding when calling all :

 if all(item in sltn for item in ("0", "1", "2")): ... 

If you're fine, if any of them are inside the list, you can use any instead:

 if any(item in sltn for item in ("0", "1", "2")): ... 
+1
source

If you do not want to waste time and sort through all the data in your list, as is widely suggested here, you can do the following:

 a = ['1', '2', '3'] b = ['4', '3', '5'] test = set(a) & set(b) if test: print('Found it. Here it is: ', test) 

Of course you can do if set(a) & set(b) . I did not do this for demonstration purposes. Please note that you must not replace & with and . These are two significantly different operators.

The above code displays:

 Found it. Here it is: {'3'} 
0
source

Source: https://habr.com/ru/post/1242655/


All Articles