【问题标题】:How to transform a slice to a list of index in python? [closed]如何将切片转换为python中的索引列表? [关闭]
【发布时间】:2019-02-05 01:16:51
【问题描述】:

我想在某个索引中转换切片,以便一次访问向量的每个元素。

我该怎么做?

【问题讨论】:

标签: python python-3.x indexing slice


【解决方案1】:

您可以使用切片的indices 方法生成一个可以传递给range 的元组。不过,您需要知道实例的长度。

例如:

>>> sl = slice(2)  # or wherever you get that from
>>> length = 100
>>> list(range(*sl.indices(length)))
[0, 1]

【讨论】:

  • 谢谢你的回答,为什么会有“*”?
  • 解包元组并将每个元素作为单独的参数传递。这是必需的,因为 range 需要 3 个整数参数而不是一个包含 3 个整数的元组。
猜你喜欢
  • 2012-06-14
  • 1970-01-01
  • 2018-10-27
  • 2021-01-13
  • 1970-01-01
  • 2021-07-25
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多