[英]How to check whether a tuple exists in a Python list?
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]]
. 我是Python新手,我试图检查列表中是否存在一对[a,b]
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? 那怎么实现呢?
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. 如果你需要这么做很多时候考虑使用set
,因为它有一个更快的收容检查。
The code does not work because '1' != 1
and, consequently, ['1','2'] != [1,2]
If you want it to work, try: 代码不起作用,因为'1' != 1
,因此, ['1','2'] != [1,2]
如果你想让它起作用,试试:
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) (但是如上所述使用in
或sets更好)
In my interpreter (IPython 0.10, Python 2.7.2+) your code gives the correct output: 在我的解释器(IPython 0.10,Python 2.7.2+)中,您的代码提供了正确的输出:
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. 原来你有在字符串a
列表。 Then you need to convert your int
s to str
as well: 然后你需要将你的int
转换为str
:
a=[['1','2'],['1','3']]
for i in range(3):
for j in range(3):
if [str(i), str(j)] in a:
print a
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. 肯定你在第一行中缺少']'。
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: 不要忘记[a,b]不是python中的[b,a]所以如果你想考虑[A,B]和[B,A]是相同的,你可能想要在你的元组中排序2个值:
You might also want to use set(your_list) if your list is big and it has redundancy. 如果列表很大且有冗余,您可能还想使用set(your_list)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.