0

我有一个 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)]
4

2 回答 2

1

如果你想要随机顺序,你应该使用random模块,特别是random.sample

于 2014-03-13T18:32:00.533 回答
1

如果你想要一个特定的顺序,你可以把它作为字典的输入,如果你间接地作为一个生成器表达式来做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']

BlueMonday = OrderedDict((x, ElementDict[x]) for x in NewOrder)

print BlueMonday
OrderedDict([('Be', (3, 9.012182)), ('C', (5, 12.0107)), ('H', (0, 1.00794))])
print BlueMonday.items()
[('Be', (3, 9.012182)), ('C', (5, 12.0107)), ('H', (0, 1.00794))]

这与您已经在做的类似,但可能不那么笨拙?

于 2014-03-13T19:07:43.400 回答