提问人:nmb 提问时间:4/2/2019 最后编辑:nmb 更新时间:4/2/2019 访问量:130
python 选择解释列表索引重新分配的动机是什么?
What is the motivation behind python's choice for interpretation of list indexing reassignment?
问:
我是 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 到底在做什么?
答: 暂无答案
评论
s[i:j:k] = t
l[::2] = [1,2]