(我使用的是Python 3.8) 問題如下:我有以下資料
items = [{season: 3, id: 1}, {season: 5, id: 2}, {season: 10, id: 3}, {season: 8, id:4}]
我想重新排列這個串列,將季節中的元素移到頭部,例如 8 和 10。為此,我有另一個串列,其中包含來自該子集的元素:
items_to_top = [{season: 10, id: 3}, {season: 8, id:4}]
我知道這不是最有效的方法,但它必須是這樣的,因為我必須尊重一些介面。為了將它們移到我正在做的前一個串列的頂部
for item in items_to_top:
items.remove(item)
items.insert(0, item)
這個操作是安全的,因為items_to_top它是從 中提取的items,因此是一個閉集。
我正在尋找一種更有效/更快的方法來執行此操作,因為當items增長(大約 30k 個元素)和items_to_top增長(大約 7k 個元素)時,回圈需要接近 1 分鐘才能完成。
我試圖將所有內容轉換為,set但我不能,因為我的資料是不可散列的(字典),并且字典的值內部也是不可散列的型別(串列)。
uj5u.com熱心網友回復:
您可以使用字典的值創建一組元組并創建一個新串列,如下所示:
top_set = {(d[season], d[id]) for d in items_to_top}
new_items = items_to_top [d for d in items if (d[season], d[id]) not in top_set]
這里的問題是每次你使用items.insert(0, item)你都是從頭開始創建一個新串列。此外,remove需要從串列的開頭到結尾搜索正確的值。
編輯:另一種方法,因為你不能散列字典中的所有元素。
for item in items_to_top:
items.remove(item)
items.append(item)
items = items[::-1]
uj5u.com熱心網友回復:
您是否可以存盤頂部專案的索引而不是(或除了) items_to_top 串列?
這將允許使用索引而不是搜索更直接地重組專案串列。
例如:
items = [{'season': 3, 'id': 1}, {'season': 5, 'id': 2},
{'season': 10, 'id': 3}, {'season': 8, 'id':4}]
toTop = [2,3]
items = [items[i] for i in dict.fromkeys([*toTop,*range(len(items))])]
print(items)
[{'season': 10, 'id': 3}, {'season': 8, 'id': 4},
{'season': 3, 'id': 1}, {'season': 5, 'id': 2}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420796.html
標籤:
上一篇:python中的反向排序出錯了
