为什么列表反向返回None?

时间:2019-07-04 03:27:21

标签: python

我使用反向,但是返回我无,您能帮忙吗?

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ',ls.reverse())

这是结果:

('List = ', [1, 2, 3, 4, 5, 6, 7, 8, 9])
('Reversed List = ', None)

2 个答案:

答案 0 :(得分:2)

由于reverse不会返回列表,因此会将列表更改为原位。没有返回值的方法总是返回None。试试:

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
ls.reverse()
print('Reversed List = ',ls)

或者,您可以使用带切片符号的步进值。这也具有不更改输入列表的效果:

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ',ls[::-1])

答案 1 :(得分:0)

reverse方法“就地”执行操作,因此您需要执行以下操作:

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
ls.reverse()
print('Reversed List = ', ls)

或使用不是“就地”的reversed

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ', list(reversed(ls)))

或很酷的切片方法:

ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ', ls[::-1])