【问题标题】:Dictionary comprehension out of list of tuples [closed]元组列表中的字典理解[关闭]
【发布时间】:2021-11-12 03:12:30
【问题描述】:

我有以下例子:

my_list = [(1, 'old', 'new'),
           (2, 'old2', 'new2'),
           (3, 'old3', 'new3')]

{x[1]:y[2] for x,y in zip(my_list,my_list)}
{'old': 'new', 'old2': 'new2', 'old3': 'new3'}

我想知道如果没有zipping 相同的可迭代my_list 两次,我是否可以实现相同的目标。

【问题讨论】:

  • 那个拉链很奇怪 :D 为什么? xy 将具有相同的值。毕竟,两者都来自同一个列表。
  • 我猜是一大早,滑倒了:D

标签: python dictionary-comprehension


【解决方案1】:

您根本不需要 zip,只需要字典理解

{x[1]:x[2] for x in my_list}

【讨论】:

  • 谢谢,不知道怎么没试过。
【解决方案2】:

为什么要使用zip,请记住这个;

my_list = [(1, 'old', 'new'),
           (2, 'old2', 'new2'),
           (3, 'old3', 'new3')]

{x[1]:x[2] for x in my_list}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2021-03-21
    • 2016-11-09
    • 2011-03-14
    • 2012-02-14
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多