反向列表的一部分

时间:2015-03-29 14:40:07

标签: list python-3.x reverse

列出foo

foo = [5, 6, 7, 8, 9, 10, 11, 12]

如何只反转列表中索引x到y的元素?
例如:

x = 1
y = 5
# reverse foo[x:y]
foo = [5, 9, 8, 7, 6, 10, 11, 12]

3 个答案:

答案 0 :(得分:4)

Python允许您assign to slices

  

切片可以用作赋值或del中的表达式或目标   语句

因此可以在一行上完成所有事情:

foo[x:y] = foo[y-1:x-1:-1]

请注意,foo[y-1:x-1:-1]foo[x:y][::-1]的含义相同。

答案 1 :(得分:2)

它很简单:

foo[x:y] = foo[y - 1:x - 1:-1]

例如:

>>> foo = [5, 6, 7, 8, 9, 10, 11, 12]
>>> foo[1:5] = foo[4:0:-1]
>>> foo
[5, 9, 8, 7, 6, 10, 11, 12]

答案 2 :(得分:1)

def reverse(l, x, y):
    l[x:y+1] = l[y:x-1:-1]

foo = [5, 6, 7, 8, 9, 10, 11, 12]
x = 1
y = 4

reverse(foo, x, y)
print(foo) # [5, 9, 8, 7, 6, 10, 11, 12]