【问题标题】:Multiple list comprehensions in one line in pythonpython一行中的多个列表理解
【发布时间】:2023-02-14 00:29:28
【问题描述】:

我在 Python 3.9 中有以下代码:

first_entries = [r[0] for r in result]
seconds_entries = [r[1] for r in result]
third_entries = [r[2] for r in result]

其中 result 是以下形式的元组列表:

result = [(x1,x2,x3),(y1,y2,y3),...]

有没有办法将其写入一行并仅对结果进行一次迭代?

【问题讨论】:

  • 也许first_entries, seconds_entries, third_entries = zip(*result),但我还没有测试过

标签: python list


【解决方案1】:

first_entries, seconds_entries, third_entries = zip(*result)

按预期工作

【讨论】:

    【解决方案2】:
    tups = [(1,2,3), (4,5,6), (7,8,9), (10,11,12)]
    
    first_entries, second_entries, third_entries = zip(*[(tup[0], tup[1], tup[2]) for tup in tups])
    
    print(first_entries) # (1, 4, 7, 10)
    

    真的需要将这些结果分成 3 个列表吗?

    【讨论】:

      猜你喜欢
      • 2012-04-07
      • 2017-11-14
      • 2012-05-03
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多