我有一個列表「A」在元組的列表中找到一個元素
a= [(1,2),(1,4),(3,5),(5,7)]
我需要找到一個特定號碼的所有元組。說爲1它將是
result = [(1,2),(1,4)]
我該怎麼做?
我有一個列表「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]
[ (x,y) for x, y in a if x == 1 ]
又讀了起來generator functions和yield
聲明。
def filter_value(someList, value):
for x, y in someList:
if x == value :
yield x,y
result= list(filter_value(a, 1))
'如果x == 1'應該是'if x == value' – sambha 2015-04-20 15:35:47
for item in a:
if 1 in item:
print item
[tup for tup in a if tup[0] == 1]
其實是有一個聰明的辦法來做到這一點是元組的任何列表,其中每個元組的大小是2有用:您可以將列表轉換成一個單一的字典。
例如,
test = [("hi", 1), ("there", 2)]
test = dict(test)
print test["hi"] # prints 1
你如何將這個應用於Bruce的問題? – HelloGoodbye 2014-01-29 08:10:30
很好的答案(儘管可能不是這個問題)。我很好地確定一個值是否在選擇元組列表中(例如,如果測試中「hi」) – MagicLAMP 2015-11-04 00:10:29
它並不真正回答這個問題,正如MagicLAMP所暗示的那樣。具體來說,'dict(X)'將X轉換成一個字典,其中任何常見的第一個元素的最後一個元組是所使用的值。在OP的例子中,這將返回(1,4)而不是(1,2)和(1,4)。 – BBischof 2016-06-12 00:51:21
功能filter
還可以提供一種有趣的解決方案:
result = list(filter(lambda x: x.count(1) > 0, a))
其搜索元組中的列表中的任何1
發生。如果搜索被限制到所述第一元件,該解決方案可以被修改爲:
result = list(filter(lambda x: x[0] == 1, a))
使用濾波器功能:
>>> 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)]
啊,列表解析。 – HelloGoodbye 2014-01-29 08:08:11