Slicing a list using a variable, in Python

前端 未结 5 2039
攒了一身酷
攒了一身酷 2020-12-05 22:36

Given a list

a = range(10)

You can slice it using statements such as

a[1]
a[2:4]

However, I want to do th

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 23:29

    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.

    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]. Nevertheless, slice(i) will default to slice(None,i,None), which isn't the desired result.

    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}]").

    This uses the eval() builtin and an f-string where st is interpolated inside the braces. It handles precisely the usual colon-separated slicing syntax, since it just plugs in that colon-containing string as-is.

提交回复
热议问题