繁体   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