저는 주기율표와 같이 주문 된 원소 (탄소와 철)를 가진 OrderedDict를 가지고 있습니다. 임의의 순서로 요소를 뽑아 내고 임의의 순서를 유지하여 나중에 numpy를 사용하는 수학과 일치하도록해야합니다.임의의 순서로 dict/OrdredDict에서 요소를 가져옵니다.
내가 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)]
'dict' 주문은 안정적이지만 예측할 수 없습니다. 예상 주문을받는 경우 실제로 사고가 발생합니다. –
나는 그것이 사실일지도 모른다고 생각했다. 어떤 경우에는 누군가가 이해력으로 그것을하는 더 좋은 방법이 없다면 나는 그 고리를 사용해야한다. – ZSG