使用字符串参数进行Python列表切片

Zul*_*kis 0 python

可以像这样切片python列表:

>>> list=['a', 'b']
>>> list[0:1]
['a']
Run Code Online (Sandbox Code Playgroud)

但是,将索引作为字符串传递时,会引发错误:

>>> index="0:1"
>>> list[index]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)

如何将列表索引指定为字符串?什么数据类型0:1list[0:1],真的吗?

tob*_*s_k 8

n:m是一个语法糖slice.你可以使用split索引字符串,将其部分转换为整数,然后slice从中创建一个.

>>> lst = list(range(10))
>>> index = "1:4"
>>> s = slice(*map(int, index.split(':')))
>>> lst[s]
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

三个部分的工作原理相同:

>>> index = "1:9:2"
>>> s = slice(*map(int, index.split(':')))
>>> lst[s]
[1, 3, 5, 7]
Run Code Online (Sandbox Code Playgroud)

如果您想允许"空白"部分,转换会涉及更多:

>>> index = "::-1"
>>> s = slice(*[int(x) if x else None for x in index.split(':')])
>>> lst[s]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Run Code Online (Sandbox Code Playgroud)