[英]Slicing a list using a variable, in Python
Given a list给出一个列表
a = range(10)
You can slice it using statements such as您可以使用以下语句对其进行切片
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]
But that doesn't work either.但这也行不通。
Is this possible?这可能吗?
Why does it have to be a single variable?为什么它必须是单个变量? Just use two variables:只需使用两个变量:
i, j = 2, 4
a[i:j]
If it really needs to be a single variable you could use a tuple.如果它真的需要是一个单一的变量,你可以使用一个元组。
With the assignments below you are still using the same type of slicing operations you show, but now with variables for the values.通过下面的分配,您仍然使用与您展示的相同类型的切片操作,但现在使用值的变量。
a = range(10)
i = 2
j = 4
then然后
print a[i:j]
[2, 3]
>>> a=range(10)
>>> i=[2,3,4]
>>> a[i[0]:i[-1]]
range(2, 4)
>>> list(a[i[0]:i[-1]])
[2, 3]
I ran across this recently, while looking up how to have the user mimic the usual slice syntax of a:b:c
, ::c
, etc. via arguments passed on the command line.我最近遇到了这个问题,同时在查找如何让用户通过命令行上传递的参数模仿a:b:c
、 ::c
等通常的切片语法。
The argument is read as a string, and I'd rather not split on ':'
, pass that to slice()
, etc. Besides, if the user passes a single integer i
, the intended meaning is clearly a[i]
.参数被读取为字符串,我宁愿不拆分':'
,将其传递给slice()
等。此外,如果用户传递单个整数i
,则预期含义显然a[i]
。 Nevertheless, slice(i)
will default to slice(None,i,None)
, which isn't the desired result.尽管如此, slice(i)
将默认为slice(None,i,None)
,这不是想要的结果。
In any case, the most straightforward solution I could come up with was to read in the string as a variable st
say, and then recover the desired list slice as eval(f"a[{st}]")
.无论如何,我能想到的最直接的解决方案是将字符串作为变量st
say 读入,然后将所需的列表切片恢复为eval(f"a[{st}]")
。
This uses the eval() builtin and an f-string where st
is interpolated inside the braces.这使用eval()内置函数和f 字符串,其中st
插入大括号内。 It handles precisely the usual colon-separated slicing syntax, since it just plugs in that colon-containing string as-is.它精确地处理通常的以冒号分隔的切片语法,因为它只是按原样插入包含冒号的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.