0

周期表のように並べられた要素 (炭素や鉄など) を持つ OrderedDict があります。いくつかの要素を任意の順序で引き出し、任意の順序を保持して、後で numpy を使用して計算できるようにする必要があります。

OrderedDict でリスト内包表記を行うと、OrderedDict の順序で要素が取得されます。しかし、それを dict に変換すると、正しい任意の順序で要素が取得されます (偶然ではないことを願っています!)

もちろん、独自のループを回すと、要素を任意の順序でうまくプルできます。

明らかに同一ではない2つの(明らかに同一の)リスト内包表記の違いを誰かが明らかにすることはできますか?

コード:

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

特定の順序が必要な場合は、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))]

それはあなたがすでにやっていることと似ていますが、少しぎこちないかもしれません?

于 2014-03-13T19:07:43.400 に答える