Python 将切片作为参数传递

标签 python slice

<分区>

我想将一个切片传递给一个函数,这样我就可以选择列表的一部分。作为字符串传递是更可取的,因为我将从用户那里读取所需的切片作为命令行选项。

def select_portion(list_to_slice, slicer):
    return(list_to_slice[slicer])

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
slicer = "1:4"

print(select_portion(numbers, slicer))

我得到以下信息:

TypeError: list indices must be integers or slices, not str

这是可以理解的,但我不知道如何修改它以获得预期的输出:

[1, 2, 3]

最佳答案

只需使用切片:

def select_portion(list_to_slice, slicer):
    return(list_to_slice[slicer])

sl = slice(1, 4, None)

select_portion([1,2,3,4,5], sl)

关于Python 将切片作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55281875/

相关文章:

r - 如何在 dplyr 中使用切片来保留 R 中具有 NA 值的行

python - pyodbc,使用表变量调用存储过程

Python套接字导致挂起

python - 在 python pandas 中的 groupby 之后填写列中缺少的行

pointers - slice 结构行为

python - Pandas 意味着函数返回 NaN

python - numpy 3D图像数组到2D

arrays - 如何将 slice 转换为数组?

python - 在 eager 模式下,如何将张量转换为 ndarray

python - 如何执行列表的成对交换?