Python 将列表拆分为大小在另一个列表中给定的子列表
我有以下清单:Python 将列表拆分为大小在另一个列表中给定的子列表,python,list,Python,List,我有以下清单: l1 = [a,b,c,d,e,f,g,h,i] l2 = [1,3,2,3] 如何以这种方式拆分l1 [[a],[b,c,d],[e,f],[g,h,i]] -The first element is a list of one element because of the 1 of l2 -The second element is a list of three elements because of the 3 of l2 -The third element is
l1 = [a,b,c,d,e,f,g,h,i]
l2 = [1,3,2,3]
如何以这种方式拆分l1
[[a],[b,c,d],[e,f],[g,h,i]]
-The first element is a list of one element because of the 1 of l2
-The second element is a list of three elements because of the 3 of l2
-The third element is a list of two elements because of the 2 of l2
-The fourth element is a list of three elements because of the 3 of l2
我尝试过使用一个函数:
def divide(num, n):
return [num[i*n : (i+1)*n] for i in range(len(num)//n)]
x = divide(l2,1)
for i in range(len(l2)):
z = x[i]
divide(l1,z)
但它不起作用…代码
输出
输出
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
你可以这样做=
start = 0
sublists = []
for n in l2:
to = start + n
sublists.append(l1[start:to])
start = to
结果是您想要的列表使用显式迭代器和
itertools.islice
>>> l1 = list("abcdefghi")
>>> l2 = [1,3,2,3]
>>> itr = iter(l1)
>>> [list(islice(itr, None, x)) for x in l2]
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
使用itr
而不是l1
意味着islice
不会在每次调用时从l1
开始读取
您可以使用functools.partial
对其进行重构,使列表更具可读性:
>>> from functools import partial
>>> take = partial(islice, iter(l1), None)
>>> [list(take(x)) for x in l2]
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
使用
枚举
和切片
,可以这样做:
l1 = ['a','b','c','d','e','f','g','h','i']
l2 = [1,3,2,3]
for index, num in enumerate(l2):
sum_up = sum(l2[:index])
print(l1[sum_up:sum_up+num])
到目前为止,您尝试了什么来解决这个问题?这更像是为我做这件事,你能做到吗。
>>> l1 = list("abcdefghi")
>>> l2 = [1,3,2,3]
>>> itr = iter(l1)
>>> [list(islice(itr, None, x)) for x in l2]
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
>>> from functools import partial
>>> take = partial(islice, iter(l1), None)
>>> [list(take(x)) for x in l2]
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
l1 = ['a','b','c','d','e','f','g','h','i']
l2 = [1,3,2,3]
for index, num in enumerate(l2):
sum_up = sum(l2[:index])
print(l1[sum_up:sum_up+num])