gpt4 book ai didi

Python 切片按相反顺序赋值不起作用!为什么?

转载 作者:行者123 更新时间:2023-11-30 23:20:51 26 4
gpt4 key购买 nike

关于 Python 如何实际将列表分配给现有列表的切片的讨论不多。

例如,我执行了以下操作:

l = [1,2,3,4,5,6]

l[2:5:1] = [7,7,7]

print l #prints [1, 2, 7, 7, 7, 6]

g = [1,2,3,4,5,6]

g[5:2:-1] = [7,7,7]

print g #prints [1, 2, 3, 7, 7, 7]

h = [1,2,3,4,5,6]

h[2:5:1] = [7,7,7,7]

print h #prints [1, 2, 7, 7, 7, 7, 6]


k = [1,2,3,4,5,6]

k[5:2:-1] = [7,7,7,7]

print k #gives a runtime error

实例:http://ideone.com/0mDBg7

有人可以解释一下这是如何工作的,以及为什么最后一个示例不像上面的示例那样成功运行(针对 h 运行,但针对 k 则不运行)?

最佳答案

如果切片长度的step不为1,则切片的长度和分配的序列的长度应该匹配。

>>> k = [1,2,3,4,5,6]
>>> len(k[5:2:-1])
3
>>> k[5:2:-1] = [7,7,7] # This is okay, lengths are same.
>>> k
[1, 2, 3, 7, 7, 7]

>>> k[5:2:-1] = [7,7,7,7] # not okay
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 4 to extended slice of size 3

如果切片的长度为1(默认),则可以分配长度不同的序列;这将改变列表的长度。

>>> k[1:5] = [1]
>>> k
[1, 1, 7]

关于Python 切片按相反顺序赋值不起作用!为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com