【问题标题】:Python: one-line extend within for-loop [duplicate]Python:for循环内的单行扩展[重复]
【发布时间】:2019-07-29 11:41:57
【问题描述】:

代码:

print([some_data[name]['indices'] for name in some_data.keys()])

输出:

[[[0, 0], [1, 0], [2, 0], [2, 1]], [[3, 0], [3, 1], [1, 1], [0, 1]], ...]

期望的输出

[[0, 0], [1, 0], [2, 0], [2, 1], [3, 0], [3, 1], [1, 1], [0, 1], ...]

尝试这个方法告诉我'list'对象没有属性'result':One liner for extend loop python

是否可以对我的代码进行更改以获得单行解决方案?

提前致谢

【问题讨论】:

  • some_data[name]['indices'] 包含什么?原子值列表?
  • 我认为你不需要额外的 [] print
  • result 应该是什么?您在错误消息中提到它,但在您的代码中没有。
  • @Nobilis some_data[name]['indices'] 包含列表列表(长度为 2):[[0, 0], [1, 0], [2, 0], [2, 1]]
  • 试试这个:[e for name in some_data.keys() for e in some_data[name]['indices']]

标签: python list for-loop


【解决方案1】:
  topList = [[1,2],[3,4]]
  flatList = [item for subList in topList for item in subList]

How to make a flat list out of list of lists?

【讨论】:

    【解决方案2】:

    您将 tge 列表正确地作为单个列表。 print() 添加了额外的 []。打印向对象添加对象类型。

    【讨论】:

    • 不,它没有。
    • 你是对的。发错了。删不掉。
    【解决方案3】:

    这是你需要的吗?例如。给定:

    some_data = {'a': {'indices': [[0, 0], [1, 1]]}, 'b': {'indices': [[2, 2], [3, 3]]}}
    

    您想要子列表,对吗?所以我们可以这样做:

    [j for i in some_data for j in some_data[i]['indices']]
    

    返回:

    [[0, 0], [1, 1], [2, 2], [3, 3]]
    

    【讨论】:

    • 其实some_data的形式是{'Name1': {'indices': [[0, 0], [1, 1]]}, 'Name2': {'indices': [[2, 2], [3, 3]]}}
    • 应该还是可以的,这样不行吗?
    • 如果在实现上与@Rocky Li 的评论相同,那么是的。我只是使用他的,因为它已经适合我的使用 - 并且有效
    • 啊,是的,我没看到,被打败了
    • 感谢您的帮助:)
    【解决方案4】:

    对于刚刚使用itertools.chain 删除答案的人 - 这有效,我将接受您的答案。最终代码:

    list(itertools.chain(*[some_data[name]['indices'] for name in some_data.keys()]))
    

    编辑:决定在@Rocky Li 的回答中不使用itertools

    [e for name in some_data.keys() for e in some_data[name]['indices']]
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多