在Python中使用变量切片列表 [英] Slicing a list using a variable, in Python

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

问题描述

提供列表

a = range(10)

您可以使用诸如

a[1]
a[2:4]

但是,我想基于代码中其他位置设置的变量来执行此操作.我可以很轻松地为第一个做到这一点

However, I want to do this based on a variable set elsewhere in the code. I can easily do this for the first one

i = 1
a[i]

但是我该如何为另一个做呢?我尝试用列表编制索引:

But how do I do this for the other one? I've tried indexing with a list:

i = [2, 3, 4]
a[i]

但这不起作用.我也尝试过使用字符串:

But that doesn't work. I've also tried using a string:

i = "2:4"
a[i]

但这也不起作用.

这可能吗?

推荐答案

用于:

a = range(10)
s = slice(2,4)
print a[s]

与使用a[2:4]相同.

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

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