以任意顺序从dict / OrdredDict中提取元素

时间:2014-03-13 18:29:05

标签: python dictionary list-comprehension ordereddictionary

我有一个OrderedDict,其元素(如碳和铁)的顺序与周期表一样。我需要以任意顺序提取一些元素并保留任意顺序,以便它们匹配以后使用numpy进行数学运算。

如果我对OrderedDict进行列表理解,我会按OrderedDict顺序获取元素。但是如果我将它转换为dict,那么我会以正确的任意顺序获取元素(我希望不小心!)

当然,如果我旋转自己的循环,那么我可以按照任意顺序拉动元素。

任何人都可以说明两个(显然相同的)列表理解之间的区别,这些理解显然不完全相同。

代码:

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)]

2 个答案:

答案 0 :(得分:1)

如果您想要随机订单,则应使用random模块,特别是random.sample

答案 1 :(得分:1)

如果你想要一个特定的订单,你可以这样做作为dict的输入,如果你作为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))]

这与你现在所做的相似,但也许不那么愚蠢了?