我有一个 OrderedDict,其中元素(如碳和铁)像元素周期表一样排列。我需要以任意顺序拉出一些元素并保留任意顺序,以便它们匹配以后使用 numpy 进行的数学运算。
如果我对 OrderedDict 进行列表理解,我会得到 OrderedDict 顺序中的元素。但是如果我将它转换为字典,那么我会以正确的任意顺序获得元素(我希望不会意外!)
当然,如果我旋转自己的循环,那么我可以按任意顺序拉取元素就好了。
任何人都可以阐明显然不相同的两个(显然相同的)列表理解之间的区别。
代码:
from collections import OrderedDict
MAXELEMENT = 8
ElementalSymbols = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O']
ElementalWeights = [1.00794, 4.002602, 6.941, 9.012182, 10.811, 12.0107, 14.0067, 15.9994];
ElementDict= OrderedDict(zip(ElementalSymbols, zip(range(0, MAXELEMENT), ElementalWeights)))
NewOrder = ['Be', 'C', 'H']
# This makes NewList have the same order as ElementDict, not NewOrder.
NewList = [(k, el[1]) for k, el in ElementDict.items() if k in NewOrder]
print NewList
# Results in:
#[('H', 1.00794), ('Be', 9.012182), ('C', 12.0107)]
# We do EXACTLY the same thing but change the OrderedDict to a dict.
ElementDict= dict(ElementDict)
# Same list comprehension, but not it is in NewOrder order instead of ElementDict order.
NewList = [(k, el[1]) for k, el in ElementDict.items() if k in NewOrder]
print NewList
# Results in:
#[('Be', 9.012182), ('C', 12.0107), ('H', 1.00794)]
# And, of course, the kludgy way to do it and be sure the elements are in the right order.
for i, el in enumerate(NewOrder):
NewList[i] = (NewOrder[i], ElementDict[NewOrder[i]][1])
print NewList
# Results in:
#[('Be', 9.012182), ('C', 12.0107), ('H', 1.00794)]