假设有一个列表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=)
粗俗但简单的方法。你知道吗
这里有一种不同的方法:
示例:
你可以这样做:
印刷品:
相关问题 更多 >
编程相关推荐