python - 合并嵌套列表,将列(位于同一索引处的元素)放在一起

标签 python python-3.x python-2.7 multiple-columns

这个问题在这里已经有了答案:





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

(22 个回答)



Transpose list of lists

(13 个回答)


10 个月前关闭。




我有一个列表列表:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]
我如何能够将列表的每一列添加到空列表中。
我的意思是,lst[i][column] ,例如1,1,1然后 2,2,2等,并得到一个 新品 列表如下:
[1,1,1,2,2,2,3,3,3]
到目前为止,我已经尝试过:
pos = 0
column = 0
row = 0
i = 0
empty = []
while i < len(lst):
    empty.append(lst[i][0])
    i += 1
print(empty)

最佳答案

这是通过使用 itertools.chain() 的组合来实现此目的的功能方法和 zip() 作为:

from itertools import chain

my_list = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

new_list = list(chain(*zip(*my_list)))
哪里new_list将举行:
[1, 1, 1, 2, 2, 2, 3, 3, 3]
请参阅以下链接以了解有关这些功能的更多信息:
  • itertools.chain() document
  • zip() document
  • 关于python - 合并嵌套列表,将列(位于同一索引处的元素)放在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65761662/

    相关文章:

    python - 根据版本将 Python 中的函数缓存到磁盘并过期

    python - Python-使用opencv编写自己的函数会出错

    python - docker-py:如何检查构建是否成功?

    python-3.x - 模拟方法的返回值不起作用

    python - 无法在Python3、Ubuntu14.04中使用pip安装NumPy

    python - 在 matplotlib 中编辑轴线

    python - 测试。如何使用外键(自动)向数据库添加许多对象?

    python - 如何在Python中对范围函数的值求和

    python - 如何使用 asyncio 进行基本文件 IO

    python - 如果将 input() 转换为字符串,是否可以安全使用?