我是python的新手(使用python2.7),在按索引更新列表时,我不理解下面的行为,以及哪些设计选择可以激发这种行为。我习惯使用R,它具有完全不同的默认行为。这是否仅针对列表,还是会以任何可变序列发生?数组呢?
如果我定义了一个列表并想在列表中重新分配值,那么我会对某些行为感到困惑
>>> l = list(range(10))
>>> l[2:4] = [20, 30] # expected
>>> l
[0, 1, 20, 30, 4, 5, 6, 7, 8, 9]
>>> l[2] = [20, 30] # expected
>>> l
[0, 1, [20, 30], 30, 4, 5, 6, 7, 8, 9]
# replacement length is longer than given index range, ignores end of given range on left side
>>> l = list(range(10))
>>> l[2:3] = [20, 30, 40] # behaves as l[2:5]=[20,30,40] (unexpected)
>>> l
[0, 1, 20, 30, 40, 3, 4, 5, 6, 7, 8, 9]
# replacement length is shorter than given index range, deletes unused index/values on left side
>>> l = list(range(10))
>>> l[2:9] = [20, 30, 40] # len(l)=6 (unexpected)
>>> l
[0, 1, 20, 30, 40, 9]
# replacement length is longer than given range and outside of current length, appends to list.
>>> l = list(range(10))
>>> l[9:len(l)] = [20, 30, 40] # last value changed, len(l)= 12 (unexpected)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 20, 30, 40]
在R(3.2.3)中,行为如下(请注意,R使用1作为第一个索引,并包含最后一个索引,使得2:3是python的2:4)
> l = 0:9
> l[2:3] = c(20, 30)
> l
[1] 0 20 30 3 4 5 6 7 8 9
# replacement length is longer than given index range, values beyond given index range are ignored
> l = 0:9
> l[2] = c(20, 30)
Warning message:
In l[2] = c(20, 30) :
number of items to replace is not a multiple of replacement length
> l
[1] 0 20 2 3 4 5 6 7 8 9
# replacement length is longer than given index range, values beyond given index range are ignored
> l = 0:9
> l[2:3] = c(20, 30, 40)
Warning message:
In l[2:3] = c(20, 30, 40) :
number of items to replace is not a multiple of replacement length
> l
[1] 0 20 30 3 4 5 6 7 8 9
# replacement length is shorter than given index range, values repeated until index range is met
> l[2:9] = c(20,30,40)
> l
[1] 0 20 30 40 20 30 40 20 30 9
# replacement length is longer than given index range, values beyond given index range are ignored
> l = 0:9
> l[9:length(l)] = c(20,30,40)
Warning message:
In l[9:length(l)] = c(20, 30, 40) :
number of items to replace is not a multiple of replacement length
> l
[1] 0 1 2 3 4 5 6 7 20 30
因此,简而言之,R假定左侧给出的范围比右侧给出的范围更可信,并且忽略或重复右侧给出的值以满足分配的左侧。
但是Python到底在做什么?