将列表拆分为另一个列表指定的大小

2024-09-28 01:32:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一个列表X和另一个列表num_items指定子列表中应包含的项目数,我可以手动拆分列表,如下所示:

>>> x = list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> num_items = [4, 4, 2]

>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):]
>>> slice1, slice2, slice3
([0, 1, 2, 3], [4, 5, 6, 7], [8, 9])

有两种情况下,最后几个片段可能会出现问题,例如,如果我手动编写了3个片段的代码,那么可以使用空列表解决这一问题:

>>> num_items = [9, 1, 1]
>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):]
>>> slice1, slice2, slice3
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9], [])

如果有4个切片,例如:

>>> num_items = [9, 1, 1, 2]
>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):len(slice1)+len(slice2)+num_items[2]]
>>> slice4 = x[len(slice1)+len(slice2)+len(slice3): len(slice)+len(slice2)+len(slice3)+num_items[3]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'type' has no len()

期望的输出是将空列表添加到第4个片段,即:

>>> slice1, slice2, slice3, slice4
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9], [], [])

如果num_items需要小于X长度的项,只需返回num_items的和,即

>>> num_items = [4, 4]
>>> slice1, slice2
([0, 1, 2, 3], [4, 5, 6, 7])

主要的问题是有没有一种方法可以在不手动编码分割的情况下分割切片?(解决了num_items请求的项目多于X的情况,在这种情况下,应该返回空的子列表)

请记住,X的长度可能相当大(即>;1000000000),但是num_items的长度范围从1到100=)


Tags: 列表lentype情况切片itemsrange手动
3条回答

粗俗但简单的方法。你知道吗

>>> x = list(range(10))
>>> num_items = [2,3,4,1]
>>> cur_sum = 0
>>> slices = []
>>> for i in num_items:
...     slices.append(x[cur_sum:cur_sum+i])
...     cur_sum += i
... 
>>> slices
[[0, 1], [2, 3, 4], [5, 6, 7, 8], [9]]

这里有一种不同的方法:

[[x.pop(0) for _ in x[:s]] for s in num_items]

示例:

>>> x = range(10)
>>> n = [9, 1, 1]
>>> [[x.pop(0) for y in x[:s]] for s in n]
[[0, 1, 2, 3, 4, 5, 6, 7, 8], [9], []]

>>> x = range(10)
>>> n = [2, 2, 2, 2, 2, 2]
>>> [[x.pop(0) for y in x[:s]] for s in n]
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], []]

>>> x = range(10)
>>> n = [3, 4, 5, 2]
>>> [[x.pop(0) for y in x[:s]] for s in n]
[[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], []] # Notice here how slice 5 only returns 3 numbers because there are only 3 numbers left in x

你可以这样做:

>>> x = list(range(10))
>>> num_items = [9, 1, 1]
>>> s = 0
>>> for i in num_items:
...     print x[s:s + i]
...     s += i
... 

印刷品:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[9]
[]

相关问题 更多 >

    热门问题