2014-03-26 110 views
1

我想添加一些整數到python列表中的項目範圍。將整數添加到Python中列表中的特定項目?

我知道如果你想爲一個整數列表中添加項目,這是正確的:

A = 2 
B = 5 
C = 6 
mylist = [1,2,3,4,5,6,7,8] 
mylist[:] = [i+C for i in mylist] 
print mylist 

,但我想通過B.添加C到項目A,使得代替導致此列表:

mylist = [7,8,9,10,11,12,13,14] 

我會得到這個名單:

mylist = [1,2,*9*,*10*,*11*,*12*,7,8] 

有沒有辦法做到這一點?

感謝

回答

6

分配到一個列表的片段:

>>> A = 2 
>>> B = 5 
>>> C = 6 
>>> mylist = [1,2,3,4,5,6,7,8] 
>>> mylist[A:B+1] = [i+C for i in mylist[A:B+1]] 
>>> mylist 
[1, 2, 9, 10, 11, 12, 7, 8] 
>>> 
1
for i in range(A, B+1): 
    mylist[i] += C 
1

除了@iCodez回答,如果你不想修改原來的,你可以使用如 - 否則

A = 2 
B = 5 
C = 6 
oldlist = [1,2,3,4,5,6,7,8] 
mylist = [x+C if A <= i <= B else x for i, x in enumerate(oldlist)] 
0
mylist[A:B+1] = [i+C for i in mylist[A:B+1]] 
相關問題