python - 如何在 Python 中添加一个数字来开始和停止切片对象?
问题描述
我阅读了这个关于切片的问题,以便更好地理解 Python 中的切片,但没有发现以简单的方式将切片对象的start
和增加stop
一个常量。“简单”是指:a)在同一行,b)在一个地方,c)没有额外的变量。
['a', 'b', 'c', 'd', 'e'][0:2] #works
['a', 'b', 'c', 'd', 'e'][(0:2)+1] #does not work, what I would find most convenient
['a', 'b', 'c', 'd', 'e'][(0+1):(2+1)] #works, but needs a change at two places
i = 1
['a', 'b', 'c', 'd', 'e'][(0+i):(2+i)] #works but needs an extra line and variable
在切片级别上,slice(0, 2, 1)+1
由于"unsupported operand type(s) for +: 'slice' and 'int'"
. 那么,如何以简单的方式在 Python 中添加一个数字来开始和停止切片对象的参数?
解决方案
为了避免写+i
两次,你可以做类似的事情
my_list[i:][:length]
例子:
i = 2
length = 3
print(['0', '1', '2', '3', '4', '5', '6', '7'][i:][:length])
--> output: ['2', '3', '4']
推荐阅读
- javascript - 编辑 vs 代码的语法以模拟 Codecademy
- python - Wiskerplots 不够清晰,无法分析数据
- python - 我正在尝试将 a 附加到现有文件中。为什么我需要使用.write 使用.append 时会报错
- python-3.x - 如何检查类型提示是否与代码中的 Iterable 兼容?
- symfony5 - Cannot autowire service RefreshedTokenListener: argument "$ttl" of method construct() is type-hinted "int", you should configure its value explicitly
- vue.js - vuejs动态绑定类属性中的文本
- asp.net-mvc - 如何使用代码优先在 asp.net-mvc 中创建登录页面
- ruby-on-rails - 将数据放入 s3 存储桶时出现 Aws::KMS::Errors::AccessDeniedException
- discord.py - discord.py 如何让机器人在特定时间发送消息以执行命令
- python - 通过 for 循环迭代创建日历数据 - 继续获取错误的上周天数