为什么不起作用?
# to reverse a part of the string in place a = [1,2,3,4,5] a[2:4] = reversed(a[2:4]) # This works! a[2:4] = [0,0] # This works too. a[2:4].reverse() # But this doesn't work
a[2:4]创建所选子列表的副本,该副本由反转a[2:4].reverse()。这不会更改原始列表。切片Python列表始终会创建副本-您可以使用
a[2:4]
a[2:4].reverse()
b = a[:]
复制整个列表。