在元组列表中查找元素

时间:2010-02-03 12:08:58

标签: python list search tuples

我有一个'a'列表

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

我需要找到特定数字的所有元组。说1,它将是

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

我该怎么做?

10 个答案:

答案 0 :(得分:194)

如果您只想匹配第一个号码,可以这样做:

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

如果您只是搜索其中包含1的元组:

[item for item in a if 1 in item]

答案 1 :(得分:97)

实际上有一种聪明的方法可以用于任何元组列表,每个元组的大小为2:您可以将列表转换为单个字典。

例如,

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

答案 2 :(得分:18)

阅读List Comprehensions

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

另请阅读generator functionsyield声明。

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

result= list( filter_value( a, 1 ) )

答案 3 :(得分:8)

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

答案 4 :(得分:5)

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

答案 5 :(得分:1)

使用过滤功能:

>>> 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)]

答案 6 :(得分:1)

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

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

答案 7 :(得分:0)

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

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

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

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

答案 8 :(得分:0)

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)]
>>> 

答案 9 :(得分:0)

如果要在元组中搜索元组中存在的任何数字,则可以使用

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]