How to check whether a tuple exists in a Python list?

自闭症网瘾萝莉.ら 提交于 2020-01-02 04:45:06

问题


I am new to Python, and I am trying to check whether a pair [a,b] exists in a list l=[[a,b],[c,d],[d,e]]. I searched many questions, but couldn't find precise solution. Please can someone tell me the right and shortest way of doing it?

when i run :

a=[['1','2'],['1','3']]
for i in range(3):
    for j in range(3):
        if [i,j] in a:
            print a

OUTPUT IS BLANK

how to achieve this then?


回答1:


The code does not work because '1' != 1 and, consequently, ['1','2'] != [1,2] If you want it to work, try:

a=[['1','2'],['1','3']]
for i in range(3):
    for j in range(3):
        if [str(i), str(j)] in a: # Note str
            print a

(But using in or sets as already mentioned is better)




回答2:


Here is an example:

>>> [3, 4] in [[2, 1], [3, 4]]
True

If you need to do this a lot of times consider using a set though, because it has a much faster containment check.




回答3:


In my interpreter (IPython 0.10, Python 2.7.2+) your code gives the correct output:

In [4]: a=[[1,2],[1,3]]

In [5]: for i in range(3):
   ...:         for j in range(3):
   ...:             if [i,j] in a:
   ...:                 print a
   ...: 
[[1, 2], [1, 3]]

(This should be a comment, but I can't leave them yet.)

EDIT:

Turns out you had strings in the a list. Then you need to convert your ints to str as well:

a=[['1','2'],['1','3']]
for i in range(3):
    for j in range(3):
        if [str(i), str(j)] in a:
            print a



回答4:


This code works fine for me:

>>> a = [[1, 2], [3, 4], [13, 11]]
>>> 
>>> for i in range(10):
...         for j in range(10):
...                 if [i, j] in a: 
...                         print [i, j] 
... 
[1, 2]
[3, 4]
>>> 

I'm not sure what is wrong with your code. For sure you have missing ']' in first line.




回答5:


Don't forget that [a, b] is not [b, a] in python so you might want to order the 2 values in your tuples if you want to consider [A, B] and [B, A] is the same:

You might also want to use set(your_list) if your list is big and it has redundancy.

In your code example you are compaing integers and strings :

['1', '2'] # this is a 2-list of strings '1' and '2'
[1, 2] # this is a 2-list of integers 1 and 2


来源:https://stackoverflow.com/questions/9654523/how-to-check-whether-a-tuple-exists-in-a-python-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!