在python中反转列表切片 [英] Reversing a list slice in python

查看:53
本文介绍了在python中反转列表切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 python 中反转列表的切片,但它返回一个空列表.但是当我尝试使用整个列表时,它工作正常.我在这里遗漏了什么吗?

I am trying to reverse slice of a list in python but it returns an empty list. But when I try with whole list, it works fine. Am I missing anything here?

l=[1,2,3,4,5,6,7,8]
l[::-1]=[8, 7, 6, 5, 4, 3, 2, 1]     <<< This worked fine.

l[2:5]=[3, 4, 5]
l[2:5:-1]=[]       <<< Expecting [5,4,3] here.

有什么线索吗?

推荐答案

语法总是 [start:end:step] 所以如果你倒退,你的开始需要大于结束.还要记住,它包括开始并排除结束,因此您需要在交换开始和结束后减去1.

The syntax is always [start:end:step] so if you go backwards your start needs to be greater than the end. Also remember that it includes start and excludes end, so you need to subtract 1 after you swap start and end.

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

这篇关于在python中反转列表切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆