【问题标题】:Get a list (without nested list) directly from a list comprehension [duplicate]直接从列表理解中获取列表(没有嵌套列表)[重复]
【发布时间】:2019-01-06 14:36:28
【问题描述】:

我想直接从列表理解中返回一个包含两个列表的交错元素的列表 - 不使用下一步来展平结果。有可能吗?

alist1_temp=[1, 4,2]
alist2_temp=[3, 7,4]
t=[[x,y] for x,y in zip(alist1_temp, alist2_temp)]

返回[[1, 3], [4, 7],[2, 4]]

但是我怎样才能直接从列表理解中获得[1, 3, 4, 7, 2, 4]

【问题讨论】:

    标签: python list list-comprehension


    【解决方案1】:

    只需使用 zip 即可尝试按您想要的顺序获取它:

    [i for j in zip(alist1_temp, alist2_temp) for i in j]
    

    如果您不介意顺序,请执行以下操作:

    alist1_temp + alist2_temp
    

    或通过itertools.chain 获得它,感谢@buran:

    import itertools
    
    list(itertools.chain(alist1_temp, alist2_temp))
    

    【讨论】:

    • 与链 - 为什么不只是list(itertools.chain(alist1_temp, alist2_temp))?这不是理解,但我不确定理解是严格的要求。无论如何,结果中元素的顺序是不同的。
    • @buran 对,你肯定是对的
    • @buran 已编辑,感谢您的评论
    【解决方案2】:

    如果你喜欢 numpy 的方式,你可以使用这个!

    np.vstack((alist1_temp,alist2_temp)).flatten('F')
    

    或者你也可以扁平化你的列表理解

    np.array(t).flatten()
    

    【讨论】:

      【解决方案3】:

      正如您指定的,您希望从列表理解中获取它:

      alist1_temp=[1,4,2]
      alist2_temp=[3,7,4]
      L = len(alist1_temp)+len(alist2_temp)
      t = [alist2_temp[i//2] if i%2 else alist1_temp[i//2] for i in range(L)]
      print(t) #prints [1, 3, 4, 7, 2, 4]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-09
        • 1970-01-01
        • 1970-01-01
        • 2018-01-30
        • 1970-01-01
        • 1970-01-01
        • 2017-11-09
        • 1970-01-01
        相关资源
        最近更新 更多