2017-03-09 99 views
1

讓我們說有一個列表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的長度可能相當大(即> 10,000,000,000)但num_items的長度範圍從1到100 =)

回答

3

這裏有一個不同的方法:

[[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 
+0

有點嚇人,但與您的方法相比,在1000次運行中,手動聲明切片對於每次運行平均節省0.5秒=) – alvas

4

粗糙而簡單的方法。

>>> 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]] 
+0

是的,我考慮到了這一點,但不知怎的想到了其他一些情況。混亂。謝謝!相應更新。 –

2

你可以這樣來做:

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