![](/img/trans.png)
[英]Iterate over list of lists and deduce a final list so that group by can be done on each element of final list in python
[英]Iterate Python List of Lists and Remove Final Index of Each Sublist, No Imports
有一些與此類似的問題,但不完全相同:
我想動態減少給定的輸入數組或列表列表。 例如:
matrix = [[0,1,2], [3,4,5],[6,7,8]]
從 0 開始,我需要遍歷並刪除最終索引 - 迭代。 所以我想存儲在新列表中的輸出是:
#output
[0,1,2], ,[3,4], [6]]
[0,1,2], ,[3,4], [6]] ==> which then flattens to [0,1,2,3,4,6]
這是我目前正在追求的:
def get_list(matrix, stop_index):
temp = []
for i in range(0, stop_index):
for m in matrix:
temp.append(matrix[0:stop_index])
outside_list.append(temp)
return outside_list
我相信我很清楚我對包和庫的過度依賴,所以我真的試圖在沒有外部包或導入的情況下做到這一點
感謝您的任何幫助! 我不會忘記綠色復選標記。
使用列表理解
l = [[0,1,2], [3,4,5],[6,7,8]]
ll = [ x[:len(l)-l.index(x)] for x in l]
# [[0, 1, 2], [3, 4], [6]]
print([x for y in ll for x in y ])
# [0, 1, 2, 3, 4, 6]
更簡單的語法:
matrix = [[0,1,2], [3,4,5],[6,7,8]]
outside_list = list()
for i in range(len(matrix)):
# matrix[i] is used to access very sublist in the matrix,
#[:3-i] is to slice every sublist from the beginning to (3 - current position)
outside_list.append(matrix[i][:3-i])
print(outside_list)
一些有用的參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.