簡體   English   中英

在python字典中用作鍵時引用元組的元素

[英]Referencing to elements of tuples when used as keys in a python dictionary

假設我有這本字典:

dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}

如何引用密鑰中的元素? 例如,如果程序在鍵的第二個元素中找到字符“ c”,我希望程序執行特定行。

您可以簡單地遍歷鍵並檢查以下內容:

>>> dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
>>> for key, value in dic.items():
...     if key[1] == 'c':
...         print key, value # or do something else
...
('b', 'c') 1

使用列表理解:

>>> dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
>>> lines =[dic[k] for k in dic if k[1]=='c']  #returns all matching items
>>> lines
[1]

對於鍵值對,迭代dict.iteritems

>>> [(k, v) for k, v in dic.iteritems() if k[1]=='c']
[(('b', 'c'), 1)]

如果有多條這樣的行,而您只有一條,則使用next

>>> next((dic[k] for k in dic if k[1]=='c'), None)
1

您可以通過遍歷keys()來解包所有鍵的第一和第二個元素

dic = {('a','b'): 0, ('b','c'): 1, ('d','e'): 2}
for first, second in dic.keys():
    if second == 'c':
        # execute the line you want
        pass

暫無
暫無

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

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