python每隔几步
时间: 2023-10-19 12:33:25 浏览: 178
在Python中,使用切片操作可以实现每隔几步的取值。可以使用以下代码来实现:
a = [1,2,3,4,5,6,7,8,9,10,11]
step = 3
b = [a[i:i+step] for i in range(0,len(a),step)]
print(b)
输出结果为:[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
这里的步长是通过`step`变量控制的,`range(0,len(a),step)`会生成一个从0到len(a)的序列,步长为step。然后使用列表推导式`[a[i:i+step] for i in range(0,len(a),step)]`来取出对应步长的子列表。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [应用需求:Python 中,while True一直循环跑代码,需要每隔2s(或n秒)执行一次if中的语句——实现方法(不...](https://blog.csdn.net/P13643822101/article/details/129985690)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Python3 小技巧三 每十个数取一次值](https://blog.csdn.net/qq_42142258/article/details/84976510)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文