![](/img/trans.png)
[英]How to check if the first element of each tuple inside a list is a key of a dictionary?
[英]How to create list of tuple by distributing the key to every value element inside a Python dictionary?
我有一個 python 字典如下:
A = {7: [21, 29, 43], 16: [20, 21, 37, 49], 21: [7, 16, 43], 29: [2, 7], 43: [7, 21], 46: [23, 36]}
我想將鍵分配給值列表中的每個元素並創建新的元組列表,如下所示:
B = [(7,21), (7,29), (7,43), (16,20),...]
我怎樣才能做到這一點? 任何幫助,將不勝感激。
A = {7: [21, 29, 43], 16: [20, 21, 37, 49], 21: [7, 16, 43], 29: [2, 7], 43: [7, 21], 46: [23, 36]}
a = []
for key, values in A.items():
for value in values:
a.append((key,value))
print (a)
Output:
[(7, 21), (7, 29), (7, 43), (16, 20), (16, 21), (16, 37), (16, 49), (21, 7), (21, 16), (21, 43), (29, 2), (29, 7), (43, 7), (43, 21), (46, 23), (46, 36)]
或者,使用列表推導:
a = [(key,value) for key, values in A.items() for value in values]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.