在元组列表中查找一个元素。

193

我有一个列表 'a'

a= [(1,2),(1,4),(3,5),(5,7)]

我需要找到一个特定数字的所有元组。比如说对于数字 1,它将会是

result = [(1,2),(1,4)]

我该如何做到这一点?

10个回答

313

如果你只想匹配第一个数字,可以像这样实现:

[item for item in a if item[0] == 1]

如果你只是在搜索包含数字1的元组:

[item for item in a if 1 in item]

173

实际上有一种聪明的方法适用于任何二元组列表: 将列表转换为单个字典。

例如,

test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1

17
你如何将这个应用到布鲁斯的问题上? - HelloGoodbye
7
好的回答(虽然可能不适用于此问题)。对我来说很有效,可以确定一个值是否在一组选择元组的列表中(例如,如果“hi”在test中)。 - MagicLAMP
14
正如MagicLAMP所提到的那样,这并没有真正回答问题。具体来说,dict(X)将X转换为一个字典,其中任何共同第一个元素的最后一个元组将被作为值使用。在OP的例子中,这将返回(1,4),而不是(1,2)和(1,4)。 - BBischof
这可能不是对以上问题的回答,但这正是我要找的东西。 - justin
喜欢它,谢谢分享。 - Sun Bee
可能是寻找元组列表的人最通用的,我喜欢它!谢谢。 - Czeskleba

28

阅读有关列表推导式的内容。

[ (x,y) for x, y in a if x  == 1 ]

还要阅读生成器函数yield语句。

def filter_value( someList, value ):
    for x, y in someList:
        if x == value :
            yield x,y

result= list( filter_value( a, 1 ) )

2
if x == 1 should be if x == value - sambha

12
[tup for tup in a if tup[0] == 1]

10

filter 函数也可以提供一个有趣的解决方案:

result = list(filter(lambda x: x.count(1) > 0, a))

这段代码在列表a中搜索任何出现的1元组。如果搜索仅限于第一个元素,则可以将解决方案修改为:

result = list(filter(lambda x: x[0] == 1, a))

10
for item in a:
   if 1 in item:
       print item

3
或者takewhile,(另外还演示了更多值的示例):
>>> a= [(1,2),(1,4),(3,5),(5,7),(0,2)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,a))
[(1, 2), (1, 4)]
>>> 

如果未排序,例如:
>>> a= [(1,2),(3,5),(1,4),(5,7)]
>>> import itertools
>>> list(itertools.takewhile(lambda x: x[0]==1,sorted(a,key=lambda x: x[0]==1)))
[(1, 2), (1, 4)]
>>> 

2
>>> [i for i in a if 1 in i]

[(1, 2), (1, 4)]


2
虽然正确,但这与8年前发布的被接受的答案中的[item for item in a if 1 in item]有何不同?还要注意,这也将匹配(2, 1)(4, 1) - Arjan

2

使用过滤函数:

>>> def get_values(iterables, key_to_find):
return list(filter(lambda x:key_to_find in x, iterables))
>>> a = [(1,2),(1,4),(3,5),(5,7)]
>>> get_values(a, 1)
>>> [(1, 2), (1, 4)]

-3
如果你想在元组中搜索任意存在的数字,那么可以使用:
a= [(1,2),(1,4),(3,5),(5,7)]
i=1
result=[]
for j in a:
    if i in j:
        result.append(j)

print(result)

如果你想在特定的索引中搜索一个数字,你也可以使用if i==j[0] or i==j[index]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接