我想在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
但是我想将C添加到项目A到B中,以便不会产生此列表:
mylist = [7,8,9,10,11,12,13,14]
我会得到这个清单:
mylist = [1,2,*9*,*10*,*11*,*12*,7,8]
有办法做到这一点吗?
由于
答案 0 :(得分: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 :(得分:1)
for i in range(A, B+1):
mylist[i] += C
答案 2 :(得分:1)
除了@iCodez答案,如果你不想修改原作,你可以使用if-else
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)]
答案 3 :(得分:0)
mylist[A:B+1] = [i+C for i in mylist[A:B+1]]