我有一个列表 'a'
a= [(1,2),(1,4),(3,5),(5,7)]
我需要找到一个特定数字的所有元组。比如说对于数字 1,它将会是
result = [(1,2),(1,4)]
我该如何做到这一点?
如果你只想匹配第一个数字,可以像这样实现:
[item for item in a if item[0] == 1]
如果你只是在搜索包含数字1的元组:
[item for item in a if 1 in item]
实际上有一种聪明的方法适用于任何二元组列表: 将列表转换为单个字典。
例如,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
[tup for tup in a if tup[0] == 1]
filter
函数也可以提供一个有趣的解决方案:
result = list(filter(lambda x: x.count(1) > 0, a))
这段代码在列表a
中搜索任何出现的1
元组。如果搜索仅限于第一个元素,则可以将解决方案修改为:
result = list(filter(lambda x: x[0] == 1, a))
for item in a:
if 1 in item:
print item
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)]
>>>
>>> [i for i in a if 1 in i]
[(1, 2), (1, 4)]
[item for item in a if 1 in item]
有何不同?还要注意,这也将匹配(2, 1)
和(4, 1)
。 - Arjan使用过滤函数:
>>> 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)]
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]
dict(X)
将X转换为一个字典,其中任何共同第一个元素的最后一个元组将被作为值使用。在OP的例子中,这将返回(1,4),而不是(1,2)和(1,4)。 - BBischof