簡體   English   中英

從嵌套的索引列表和嵌套的字符串列表創建字符串列表

[英]Create list of strings from nested list of indices and nested list of strings

我有兩個嵌套列表:一個包含索引列表,另一個包含字符串列表。 第 0 個索引子列表對應於第 0 個字符串子列表。 每個索引子列表的內部是我想要拉入新嵌套列表的相應字符串子列表的字符串的索引。

nested_indices = [[3,4,5],[0,1,2],[6,7,8]]
strings_list = [['0a','0b','0c','0d','0e','0f','0g','0g','0h', '0i'],
           ['1a','1b','1c','1d','1e','1f','1g','1g','1h', '1i'],
           ['2a','2b','2c','2d','2e','2f','2g','2g','2h', '2i'],
           ['3a','3b','3c','3d','3e','3f','3g','3g','3h', '3i'],
           ['4a','4b','4c','4d','4e','4f','4g','4g','4h', '4i'],
           ['5a','5b','5c','5d','5e','5f','5g','5g','5h', '5i'],
           ['6a','6b','6c','6d','6e','6f','6g','6g','6h', '6i'],
           ['7a','7b','7c','7d','7e','7f','7g','7g','7h', '7i'],
           ['8a','8b','8c','8d','8e','8f','8g','8g','8h', '8i'],
           ['9a','9b','9c','9d','9e','9f','9g','9g','9h', '9i']]

nested_indices 中的列表在使用中是可變長度的。 但是對於這個例子,這是我希望得到的:

expected=[['0d','0e','0f'],['1a','1b','1c'],['2g','2g','2h']]

到目前為止,這是我的代碼,它不僅沒有給我正確的值,而且還丟失了嵌套列表結構。

new_list = []

for sublist in nested_indices:
    for (item, index) in enumerate(sublist):
        new_list.append(strings_list[item][index])
        
print(new_list)

結果是: ['0d', '1e', '2f', '0a', '1b', '2c', '0g', '1g', '2h']

我哪里錯了?

利用:

  • zip 將兩個嵌套列表中的相應子列表配對
  • 列表推導從成對的子列表中獲取相應的值

代碼

new_list = [[vals[i] for i in idxs] for idxs, vals in zip(nested_indices, strings_list)]

結果

[['0d', '0e', '0f'], ['1a', '1b', '1c'], ['2g', '2g', '2h']]

你有 go

for i,idx in enumerate(nested_indices):
    print(i)
    nested_list=[]
    for j in idx:
        print(j)
        nested_list.append(strings_list[i][j])
    output_f.append(nested_list)

您的代碼中的問題是您沒有獲得sublist索引。 你應該枚舉兩次。

new_list = []

for sublistKey,sublistValue in enumerate(nested_indices):
    x = []
    for (item, index) in enumerate(sublistValue):
        x.append(strings_list[sublistKey][index])
    new_list.append(x)      

print(new_list) # expected result = [['0d', '0e', '0f'], ['1a', '1b', '1c'], ['2g', '2g', '2h']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM