【问题标题】:More Pythonic Way To Do This?更 Pythonic 的方式来做到这一点?
【发布时间】:2021-12-20 06:42:28
【问题描述】:

我有一个元组列表,我想将其转换为字典列表,其中对于每个元组,字典键是元组中的索引,值是该索引中的元组条目。

例如,如果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 方式的建议将不胜感激。

【问题讨论】:

  • 枚举是你要找的。​​span>

标签: python list dictionary list-comprehension


【解决方案1】:

您可以为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]

【讨论】:

  • [dict(enumerate(t)) for t in tuple_list] 也可以
【解决方案2】:

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

【讨论】:

  • 过度设计
【解决方案3】:

将每个元组的映射枚举到字典构造函数中:

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

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

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 2010-12-08
  • 1970-01-01
  • 2016-02-13
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多