如何在 Python 中反转列表的一部分(切片)? [英] How do I reverse a part (slice) of a list in Python?
本文介绍了如何在 Python 中反转列表的一部分(切片)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这不起作用?
# 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]
creates a copy of the selected sublist, and this copy is reversed by a[2:4].reverse()
. This does not change the original list. Slicing Python lists always creates copies -- you can use
b = a[:]
复制整个列表.
这篇关于如何在 Python 中反转列表的一部分(切片)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文