我有一個包含字典的串列,如下所示:
testList = [{'title': 'test1', 'path': ['a', 'b']},
{'title': 'test2', 'path': ['a', 'b']},
{'title': 'test3', 'path': ['a', 'e']},
{'title': 'test4', 'path': ['a', 'e']},
{'title': 'test5', 'path': ['a', 'z']},
{'title': 'test6', 'path': ['a', 'z']}]
我想移動path[-1] == "z"前面有test2. 我正在努力做到這一點,以便我的程式能夠找到串列中最后一個元素的索引path[-1] == "b",并將其添加到那里。
預期輸出:
[{'title': 'test1', 'path': ['a', 'b']},
{'title': 'test2', 'path': ['a', 'b']},
{'title': 'test5', 'path': ['a', 'z']},
{'title': 'test6', 'path': ['a', 'z']},
{'title': 'test3', 'path': ['a', 'e']},
{'title': 'test4', 'path': ['a', 'e']}]
我試圖這樣做:
for d in testList:
if d['path'][-1] == "b":
idx = testList.index(d)
if d['path'][-1] == "z":
testList.remove(d)
testList.insert(idx, d)
但這不起作用,它根本沒有改變串列。有人可以提供一些幫助。
uj5u.com熱心網友回復:
正如評論所示,在迭代時更改 list 的元素,在我看來,您只是在排序。首先是所有內容b,然后是所有內容,z然后是其他所有內容。
如果我們像這樣創建一個排序鍵:
sortkey = {'b' : 0 , 'z' : 1}
并像這樣使用它:
testList = sorted(testList, key = lambda x: sortkey.get(x['path'][-1],2))
測驗串列現在是:
[{'title': 'test1', 'path': ['a', 'b']},
{'title': 'test2', 'path': ['a', 'b']},
{'title': 'test5', 'path': ['a', 'z']},
{'title': 'test6', 'path': ['a', 'z']},
{'title': 'test3', 'path': ['a', 'e']},
{'title': 'test4', 'path': ['a', 'e']}]
uj5u.com熱心網友回復:
如果我猜對了您要實作的目標,則可以設定自定義排序順序
order= ['b','z']
sortedList = sorted(testList, key=lambda x: order.index(x['path'][-1]) if x['path'][-1] in order else len(order))
uj5u.com熱心網友回復:
嘗試這個。
testList = [{'title': 'test1', 'path': ['a', 'b']},
{'title': 'test2', 'path': ['a', 'b']},
{'title': 'test3', 'path': ['a', 'e']},
{'title': 'test4', 'path': ['a', 'e']},
{'title': 'test5', 'path': ['a', 'z']},
{'title': 'test6', 'path': ['a', 'z']}]
index = [i for i,v in enumerate(testList) if v['title'] == 'test2'][-1] 1 # find the index of dict with the title of test2 and add 1.
new_lst = []
for a in testList:
if a['path'][-1] == 'z':
new_lst.insert(index,a)
index =1
continue
new_lst.append(a)
print(new_lst)
uj5u.com熱心網友回復:
查找串列中最后一個帶有 'b' 值的字典。創建一個新串列,該串列由直到并包括先前找到的元素的元素組成。隨后插入或追加到新串列。
這里沒有排序,因為對“z”的檢查被認為是任意的。
testList = [{'title': 'test1', 'path': ['a', 'b']},
{'title': 'test2', 'path': ['a', 'b']},
{'title': 'test3', 'path': ['a', 'e']},
{'title': 'test4', 'path': ['a', 'e']},
{'title': 'test5', 'path': ['a', 'z']},
{'title': 'test6', 'path': ['a', 'z']}]
idx = -1
for i, d in enumerate(testList):
if d['path'][-1] == 'b':
idx = i
if (idx := idx 1) > 0:
newList = testList[:idx]
for d in testList[idx:]:
if d['path'][-1] == 'z':
newList.insert(idx, d)
idx = 1
else:
newList.append(d)
print(newList)
輸出:
[{'title': 'test1', 'path': ['a', 'b']}, {'title': 'test2', 'path': ['a', 'b']}, {'title': 'test5', 'path': ['a', 'z']}, {'title': 'test6', 'path': ['a', 'z']}, {'title': 'test3', 'path': ['a', 'e']}, {'title': 'test4', 'path': ['a', 'e']}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488137.html
標籤:Python python-3.x 列表 字典 索引
上一篇:只保留嵌套字典的第一個元素
下一篇:有效計算字典中鍵的平均值
