[英]Iterate a list on a specific range of indexes and get the elements of the sub-lists in these indexes
我需要遍歷列表列表,僅在從另一個列表給出的特定索引范圍內迭代,並僅獲取這些索引中子列表的元素
我創建了一個讀取列表列表的列表理解: common_a[ ]然后我需要迭代這個列表的特定索引范圍(該范圍是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] ]
但它不起作用,經過上述多次組合和許多小時的工作,我遇到了任何幫助,非常歡迎提出建議,謝謝!
您可能需要以下嵌套列表hits_idx1
,您可以直接遍歷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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.