python - 压缩列表的递归方法?

标签 python

我有一个嵌套的列表,如下所示,

list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

但是,我想找到一种方法将每个列表的第一个索引与另一个列表的第一个索引连接起来。

list1 = [[1,4,7,10],[2,5,8,11],[3,6,9,12]]

我尝试使用以下代码进行列表推导

list1 = [[list1[j][i] for j in range(len(list1)) ] for i in range(len(list1[0])) ]

# gives me
# list1 = [[1,4,7,10],[2,5,8,11],[3,6,9,12]]

但是,我希望有其他方法可以达到相同的结果,希望是更简单、更优雅的方法。

提前致谢。

最佳答案

zip是内置方法,不需要外部包:

>>> list1 = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> print([list(x) for x in zip(*list1)])
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

注意 *list1!这是必需的,因为 list1 是一个嵌套列表,因此 * 将该列表的元素解压缩到 zip 方法以压缩在一起。然后,由于 zip 返回一个元组列表,我们只需将它们转换为列表(根据您的要求)

关于python - 压缩列表的递归方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57028331/

相关文章:

python - Sqlite Server 版本不同

Python——列表索引超出范围——在一个简单的 SELECT 语句上?

python - 无法将字符串转换为 int

python - 使用 QMediaPlayer.duration() 时总是得到 0

python - Pandas :Dataframe.replace() 与正则表达式

python - 重新采样 Pandas 时间序列以获得 bin 名称的结束时间戳?

python - 从变量更新 Tkinter 标签

python - 链接回 Sphinx 中的源代码文件

python - 从 Jupyter Notebook 中安装 pip 包不起作用

python - 获取 Firestore 集合大小