遍历特定范围索引的列表,并获取这些索引中子列表的元素

时间:2018-12-28 20:08:54

标签: python list list-comprehension

我只需要遍历列表列表,仅在另一个列表给出的特定索引范围内,并仅获取那些索引中的子列表元素

我创建了一个列表理解,它读取一个列表列表: common_a [] 然后我需要遍历该列表的特定索引范围(该范围是< em> hits_idx1 [] 列表),以便进一步使用这些索引下的子列表的内容:

hits_idx1 = [5,4] # use the indexes of this list as a range [0,1]
common_a = [[23],[3,8,2,5],[2,1]] # iterate on the [0,1] range indexes only


s = [ [ data_db[0][x] for x in common_a[] ],
      [ data_db[2][x] for x in common_a[] ],
      [ ....                              ]  ] 

我无法确定如何遍历特定范围的索引,我需要以下内容:

[ data_db[0][x] for x in common_a[ [index for index, value in enumerate(hit_idx1)] ]

但是它不起作用,因为这会产生一个列表,所以我尝试遍历所产生的索引列表:

[ data_db[0][x] for x in common_a[y] for y in [0,1] ]

但这是行不通的,经过以上许多小时的组合,我束手无策,建议非常欢迎!

1 个答案:

答案 0 :(得分:1)

您可能需要以下嵌套列表理解:直接在hits_idx1上进行迭代以获取索引,然后将其传递给common_a以在相应的子列表中获取子列表指数。然后,您可以遍历该子列表以使用其在data_db

中的元素

在无法访问样本输入和所需输出的情况下,这一切现在都是沉思的。请尝试以下代码,并在注释中告知我,是否可以使用,是否需要进行任何更改。

hits_idx1 = [5,4] # use the indexes of this list as a range [0,1]
common_a = [[23],[3,8,2,5],[2,1]]

desired = [data_db[0][x] for ind in hit_idx1 for x in common_a[ind]]