Python 将列表 reshape 为多维列表

标签 python python-3.x list multidimensional-array

我有一个列表,每个维度的长度都不同,如下所示:

list1=[[2,3,4],[1],[77,8,27,12],[25,15]]

我还有另一个包含相同数量元素的列表,例如:

list2=[a,b,c,d,e,f,g,h,i,j]

我想将我的 list2 reshape 为 list1 并在 for 循环中一起处理两个列表。

最佳答案

这是一种可爱的方式。

list1 = [[2,3,4],[1],[77,8,27,12],[25,15]]
list2 = list("abcdefghij")

list2_iterator = iter(list2)
list2_reshaped = [[next(list2_iterator) for _ in sublist] for sublist in list1]

print(list2_reshaped)

Out: [['a', 'b', 'c'], ['d'], ['e', 'f', 'g', 'h'], ['i', 'j']]

我不知道纯粹的理解是否可能。

关于Python 将列表 reshape 为多维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029708/

相关文章:

python - 通过 __init__ 构造对象并忽略构造函数异常

list - 在多行 SQLite 表中查找重复项

python - 如何找到第n次出现在列表中的项目的索引?

c# - 排序列表或二叉搜索树

python - 对应于所有唯一行的所有行的平均值

python - 无法将keras模型转换为tensorflow : type object 'Dense' has no attribute 'from_config'

python - 如何在拆分字符串和数字之前避免包含字符串和数字的行?

python - 如何修复 'cannot import name ' ' 错误中的 'pdfminer.pdfinterp' process_pdf'

python-3.x - py.test 中的并行测试

python - 如何在 python3.6 中将包含键和值列表的字典初始化为空集?