我有两个清单:
list1 = [1, 2, 1, 2, 3, 2, 4, 1]
list2 = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]
我想创建一个新的元组列表,如下所示:
result = [
(a,),
(b, c),
(d,),
(e, f),
(g, h, i),
(j, k),
(l, m, n, o),
(p,)
]
答案 0 :(得分:1)
您可以在生成器中执行此操作:
def divvy_up(lst, lengths):
pos = 0
for length in lengths:
yield tuple(lst[pos:pos + length])
pos += length
将为lst
中指定的每个长度生成取自lengths
的元组:
>>> import string
>>> list1 = [1, 2, 1, 2, 3, 2, 4, 1]
>>> list2 = list(string.ascii_lowercase[:16])
>>> list2
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
>>> list(divvy_up(list2, list1))
[('a',), ('b', 'c'), ('d',), ('e', 'f'), ('g', 'h', 'i'), ('j', 'k'), ('l', 'm', 'n', 'o'), ('p',)]
要将此扩展到任何 iterable (而不是像列表这样的序列),您可以在此处使用itertools.islice()
:
from itertools.islice
def divvy_up(it, lengths):
it = iter(it)
for length in lengths:
yield tuple(islice(it, length))
答案 1 :(得分:0)
cumsum = [sum(list1[0:i]) for i in range(1, len(list1) + 1)]
[tuple(list2[a:b]) for a, b in zip([None] + cumsum[0:-1], cumsum)]
给出答案