Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表拆分为大小在另一个列表中给定的子列表_Python_List - Fatal编程技术网

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