我正在使用 Python 字典列表。我试图通过将字典项目移动到顶部来对列表进行排序。但是, list.insert(0, dictItem) 不起作用,因为我希望每次迭代都插入到列表顶部。 (即下推堆栈)但它将第一次迭代放在索引 0 处,下一次迭代放在索引 1 处。
我错过了什么?
theList = [{"V":"1"},{"V":"2"},{"V":"3"},{"V":"4"},{"V":"5"}]
i = -1
for vMove in {"4", "5"}:
for listDict in theList:
i += 1
vName = listDict.get("V")
if(vName == vMove):
break
theList.insert(0, theList.pop(i))
i = -1
print(theList)
#Expected Result: [{'V': '5'}, {'V': '4'}, {'V': '1'}, {'V': '2'}, {'V': '3'}]
#Actual Result: [{'V': '4'}, {'V': '5'}, {'V': '1'}, {'V': '2'}, {'V': '3'}]
是的,我知道我可以重新订购 vMove,但我很好奇为什么它会这样工作。
正如@001所提到的,集合是无序的。 OP 使用集合
{'4', '5'}
而不是有序列表或元组:
>>> print({'4', '5'}) # set (unordered, implementation defined, could vary by implementation)
{'5', '4'}
>>> print(('4', '5')) # tuple (consistent order).
('4', '5')
enumerate
而不是尴尬的 i
实现):
theList = [{'V': '1'}, {'V': '2'}, {'V': '3'}, {'V': '4'}, {'V': '5'}]
for vMove in ('4', '5'): # tuple
for i, listDict in enumerate(theList):
vName = listDict.get('V')
if vName == vMove:
break
theList.insert(0, theList.pop(i))
print(theList)
输出:
[{'V': '5'}, {'V': '4'}, {'V': '1'}, {'V': '2'}, {'V': '3'}]