Python列表理解从平面列表映射到模仿嵌套结构

时间:2013-11-20 01:37:43

标签: python list-comprehension

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] ]

我有一个丑陋的循环,但似乎不能让它理解得出来。

ETA:嗯。我根据示例中使用的整数类型看到了一些很酷的答案。我应该补充一点,它需要处理字符串。

让我更加透明和准确。

我有一个句子已被分解为基于空格的标记和子标记,以及一个替换标记的平面列表。

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', '.']]

4 个答案:

答案 0 :(得分:6)

此方法仅依赖于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', '.']]

答案 1 :(得分:1)

这似乎有效。

>>> [[list1[i] for i in s] for s in list2]
[[3, 5], [4, 1, 2], [6], [0, 7]]

答案 2 :(得分:1)

使用嵌套的list-comp来使用第二个列表中的值来获取第一个:

list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]    
list3 = [[list1[i] for i in el] for el in list2]
# [[3, 5], [4, 1, 2], [6], [0, 7]]

答案 3 :(得分:0)

也许你可以试试这个:

list1 = [3, 5, 4, 1, 2, 6, 0, 7]
list2 = [ [0,1], [2,3,4], [5], [6,7] ]
print([list1[l[0] : l[0] + len(l)] for l in list2])