在 recent question 中, thefourtheye展示了将列表映射到嵌套列表的简洁列表理解:
list1 = [1, 2, 3, 4, 5]
list2 = [[1, 2, 3], [5], [1, 6], [1, 0, 9, 10], [1, 5, 2]]
print [(item1, s) for item1, item2 in zip(list1, list2) for s in item2]
输出
[(1, 1), (1, 2), (1, 3), (2, 5), (3, 1), (3, 6), (4, 1), (4, 0), (4, 9), (4, 10), (5, 1), (5, 5), (5, 2)]
我的问题是相关的。
是否有一个列表理解来获取 n 个元素的平面列表,并将其映射到具有 n 个基本元素的嵌套列表的结构中?:
list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]
输出
[ [3,5], [4,1,2], [6], [0,7] ]
我有一个丑陋的循环,但似乎无法理解它。
预计到达时间:嗯。基于我在示例中使用的整数类型,我看到了一些很酷的答案。我应该补充说它需要处理字符串。
让我更透明和准确。
我有一个句子已被分解为基于空格的标记和子标记,以及替换标记的简单列表。
list2 = [['This'], ['is'], ['a'], ['sentence'], ['I', "'d"], ['like'], ['to'], ['manipulate', '.']]
list1 = ['These', 'were', 'two', 'sentences', 'I', "'d", 'like', 'to', 'read'.]
output = [['These'], ['were'], ['two'], ['sentences'], [['I'], ["'d"]], ['like'], ['to'], ['read', '.']]
最佳答案
这个方法只依赖于 list2 的“形状”,而不是内容
>>> list1 = [3, 5, 4, 1, 2, 6, 0, 7]
>>> list2 = [ [0,1], [2,3,4], [5], [6,7] ]
>>> it = iter(list1)
>>> [[next(it) for i in el] for el in list2]
[[3, 5], [4, 1, 2], [6], [0, 7]]
以字符串为例
>>> list2 = [['This'], ['is'], ['a'], ['sentence'], ['I', "'d"], ['like'], ['to'], ['manipulate', '.']]
>>> list1 = ['These', 'were', 'two', 'sentences', 'I', "'d", 'like', 'to', 'read','.']
>>> it = iter(list1)
>>> [[next(it) for i in el] for el in list2]
[['These'], ['were'], ['two'], ['sentences'], ['I', "'d"], ['like'], ['to'], ['read', '.']]
关于Python 列表理解从平面列表映射以模仿嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20085745/