簡體   English   中英

更 Pythonic 的方式來做到這一點?

[英]More Pythonic Way To Do This?

我有一個元組列表,我想將它轉換為字典列表,其中對於每個元組,字典鍵是元組中的索引,值是該索引中的元組條目。

例如,如果tuple_list=[('a','b','c'), ('e','f','g')]那么目標是processed_tuple_list = [{0:'a',1:'b',2:'c'},{0:'e',1:'f',2:'g'}]

我目前的解決方案是有一個功能

def tuple2dict(tup):
    x = {}
    for j in range(len(tup)):
        x[j]=tup[j]
    return x

然后調用[tuple2dict(x) for x in tuple_list] 我懷疑有一種列表理解方式可以做到這一點,我最初嘗試這樣做

[{j:x[j]} for x in tuple_list for j in range(len(x))]

但這只是給了我一個[{0:'a'},{1:'b'},...] 任何關於更pythonic方法的建議將不勝感激。

您可以為list每個元組創建dict ,如下所示:

>>> tuple_list=[('a','b','c'), ('e','f','g')]
# Expanded solution for more explanation
>>> [{idx: val for idx, val in enumerate(tpl)} for tpl in tuple_list]
[{0: 'a', 1: 'b', 2: 'c'}, {0: 'e', 1: 'f', 2: 'g'}]

感謝@ddejohn 最短方法:

>>> [dict(enumerate(t)) for t in tuple_list]

您可以使用 zip [dict(zip(range(len(tp)),tp))) for tp in tuple_list]

映射枚舉到每個元組的字典構造函數中:

processed_tuple_list = [*map(dict,map(enumerate,tuple_list))]

[{0: 'a', 1: 'b', 2: 'c'}, {0: 'e', 1: 'f', 2: 'g'}]

暫無
暫無

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

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