簡體   English   中英

在元組列表中查找元素

[英]Find an element in a list of tuples

我有一個列表“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]

實際上有一種聰明的方法可以做到這一點,它對於每個元組大小為 2 的任何元組列表都很有用:您可以將列表轉換為單個字典。

例如,

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

閱讀列表理解

[ (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 ) )
[tup for tup in a if tup[0] == 1]
for item in a:
   if 1 in item:
       print item

filter函數還可以提供一個有趣的解決方案:

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

它在列表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)]
>>> [i for i in a if 1 in i]

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

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

如果要搜索元組中存在的任何數字的元組,則可以使用

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM