从列表中切出n个点或尽可能多的点。

问题描述 投票:0回答:1

我在用python slicing从一个列表中取元素,但不知道里面的元素会不会够用。

目前我是这样做的,感觉很丑。

        if index + num_to_take > len(values):
            bit = values[index: ]
        else:
            bit = values[index:index + num_to_take]

有没有更好的方法?

python slice
1个回答
1
投票

你可以跳过 if 条件完全。

bit = values[index:index + num_to_take] 会运行得很好。

利用python中slicing的工作原理。阅读 这个 以获取更多信息。


1
投票

没有必要的如果

bit = values[index:index + num_to_take] 行得通

© www.soinside.com 2019 - 2024. All rights reserved.