简体   繁体   English

如何将值列表转换为列表中的索引/切片?

[英]How can I convert a list of values into an index/slice from a list?

I have a list that contains many elements, where each element represents an input file, that I want to dynamically subset using the values contained within another list.我有一个包含许多元素的列表,其中每个元素代表一个输入文件,我想使用另一个列表中包含的值对其进行动态子集化。 For example, I have some code that dynamically generates lists that I want to use to define the sub-samples such as例如,我有一些代码可以动态生成我想用来定义子样本的列表,例如

[0, 1, 2, 3]

and

[1, 2, 3, 4]

But I want to use the start and end elements of each of these lists to define an slice range to be applied to another list.但我想使用每个列表的开始和结束元素来定义要应用于另一个列表的切片范围。 In other words, I want the two above lists to be converted into slices that look like this换句话说,我希望将上面的两个列表转换成看起来像这样的切片

[0:3] and [1:4] [0:3][1:4]

But I don't know how to do this, and to be honest I'm not even sure the correct terminology to use to search for this.但我不知道如何做到这一点,老实说,我什至不确定用于搜索这个的正确术语。 I have tried searching stack overflow for 'dynamically generate slices from lists' or even 'dynamically generate data slice' (an variants that I can think of along those lines) without any success.我尝试在堆栈溢出中搜索“从列表动态生成切片”甚至“动态生成数据切片”(我可以沿着这些思路想到的变体),但没有任何成功。

Here are a few more details:以下是更多细节:

thislist = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf', '2020/01/16/zpqr', '2020/01/15/zpqr', '2020/01/15/juwi']

where someIndexSlice is [0:3] and generated from a list that looks like this [0,1,2,3]其中 someIndexSlice 是[0:3]并从看起来像这样[0,1,2,3]的列表生成

thislist[someIndexSlice] = ['2019/12/26/fjjd', '2019/12/26/defg', '2020/01/09/qpfd', '2020/01/09/tosf']

So my questions are:所以我的问题是:

  1. How can I accomplish this?我怎样才能做到这一点?
  2. What sort of terminology should I use to describe what I am trying to accomplish?我应该使用什么样的术语来描述我想要完成的事情?

Thanks谢谢

You can use the built-in slice function:您可以使用内置slice function:

>>> lst = [0, 1, 2, 3]
>>> as_slice = slice(lst[0], lst[-1], lst[1] - lst[0])
>>> as_slice
slice(0, 3, 1)        # which is same as [0:3]

And then to check if it works correctly:然后检查它是否正常工作:

>>> test = [1, 5, 3, 7, 8]
>>> test[as_slice]
[1, 5, 3]
>>> test[0:3]
[1, 5, 3]

NOTE: This implementation assumed your list s are equidistant, and sorted.注意:此实现假设您的list是等距且已排序的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM