2012-04-10 31 views
9

我有一個簡單,總是連續有序列表如下:如何在Python中刪除列表的範圍(小節)?

all = [ 1, 2, 3, 4, 5, 6 ] # same as range(1, 7) 

我也有current = 4。最後,我想all列表看起來像這樣

altered = [ 1, 2, 5, 6 ] 

到底發生了什麼是它去掉了current數量和的一個前3

current也可以是10,所以我想確保它不會爲這兩個值拋出錯誤。

對於異常current = 0,改變列表是這樣

altered = [ 1, 2, 3, 4, 5 ] 

這意味着current = 0簡單地刪除最後一個數字。

我覺得你可以用發生器編寫一些奇特的東西,但是我會寫它們。

在此先感謝!

獎勵積分在一行中做到這一點。如果current = 0太麻煩了,那麼它也可能是current = -1current = 7

編輯:確保檢查current = 1,這應該是

altered = [ 2, 3, 4, 5, 6 ] 
+0

當電流== 4是4從列表中刪除,因爲它具有值4或者是因爲它是在第四位置(從一個計數時)?同樣,是否刪除了3,因爲它是小於4的最小數字,還是因爲它位於刪除項目之前的索引? – thebjorn 2012-04-10 07:28:41

+0

該列表總是一個'range()',因此無論您將其視爲位置還是值,都無關緊要。 – hobbes3 2012-04-10 07:30:38

+2

不要將你的列表調用爲'all',因爲有一個內置的函數'all()',並且一旦你使用這個名字就刪除對它的訪問。 – jamylak 2012-04-10 07:35:04

回答

9
all = all[:max(current - 2, 0)] + all[current:] 

del all[max(current - 2, 0):current] 
+0

不適用於'current = 1' – hobbes3 2012-04-10 07:20:47

+0

它現在有效嗎? – Doboy 2012-04-10 07:23:46

+0

不錯!這也適用於'current = 7'。是否可以使它刪除'current = 0'的最後一個數字?那麼它會很完美! – hobbes3 2012-04-10 07:27:59

1

將這項工作?

>>> all = range(1, 7) 
>>> new = all[:2]+all[4:] 
>>> print new 
[1, 2, 5, 6] 
0
>>> all = range(1,7) 
>>> current = 4 
>>> [item for item in all if item != current and item != current-1] 
[1, 2, 5, 6] 
>>> current = 0 
>>> [item for item in all if item != current and item != current-1] 
[1, 2, 3, 4, 5, 6] 
+0

順便說一句,這使原始列表保持不變。 – huggie 2012-04-10 07:22:24

+1

'current = 0'必須刪除最終值'6'作爲** hobbes3 **提到 – FallenAngel 2012-04-10 07:25:18

+0

我覺得這樣可以工作,但是它不適用於'current = 0' :-('[item中的項目全部如果item!= current和item!= current-1或current == 0並且item!= len(全部)]' – hobbes3 2012-04-10 07:51:36

1
all[:max(current-2,0)] + all[max(current,0):][:-1] + all[-1:]*(0 < current < len(all))