簡體   English   中英

根據元組列表中的第二個值找到元組后返回元組的第一個元素

[英]Returning first element of a tuple after finding the tuple according to the second value in a list of tuples

我有一個看起來像這樣的元組列表:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

根據第二個值找到所述元組后,我想返回元組的第一項。 我可以做這樣的事情:

for pair in list_of_tuples:
    if pair[1] == something:
        print(pair[0])

# or

[pair[0] for pair in e1_span_sent_pairs if pair[1] == something][0]

但我想知道是否有一種方法可以在不使用 for 循環的情況下做到這一點。 謝謝。

您可以創建一個 dict,因此 ot 是可重用的,如下所示:

list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]

d = {v: (k, v) for k, v in list_of_tuples}

print(d['a'])
print(d['c'])

輸出:

(1, 'a')
(3, 'c')

如果for循環惹惱你,這將導致相同的dict

d = dict(map(lambda tup: (tup[1], (tup[0], tup[1])), list_of_tuples))

如果您真的不想要循環(即使不是簡單列表理解的形式),您可以執行以下操作:

result = map(lambda i: i[0], filter(lambda i: i[1] == 'c', list_of_tuples))

但我只是使用列表理解並解包元組的兩個元素:

result = [l for l ,r in list_of_tuples if r == something]

暫無
暫無

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

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