2012-11-12 43 views
0

使用單個語句,打印僅包含原子符號及其對應於wts(我的詞典)中的元素的相應權重的字典,這些元素的原子符號中只有一個字母。即,包括'H'但省略'他'。我的字典裏被設置爲{'H':'1.00794','He':'4.002602','Li':'6.941','Be':'9.012182','B':'10.811','C':'12.0107','N':'14.0067','O':'15.9994'}嘗試使用列表理解過濾詞典

[for element in wts if len(element) == 1] 

我在想一個列表解析會的工作,但,我如何讓它看起來只在元素符號。這將返回一個錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "_sage_input_45.py", line 10, in <module> 
    exec compile(u"print _support_.syseval(python, u'[for element in wts if len(element) == 1]', __SAGE_TMP_DIR__)" + '\n', '', 'single') 
    File "", line 1, in <module> 

    File "/sagenb/sage_install/sage-5.3-sage.math.washington.edu-x86_64-Linux/devel/sagenb-git/sagenb/misc/support.py", line 487, in syseval 
    return system.eval(cmd, sage_globals, locals = sage_globals) 
    File "/sagenb/sage_install/sage-5.3-sage.math.washington.edu-x86_64-Linux/local/lib/python2.7/site-packages/sage/misc/python.py", line 53, in eval 
    eval(compile(s, '', 'exec'), globals, globals) 
    File "", line 3 
    [for element in wts if len(element) == 1] 
    ^
SyntaxError: invalid syntax 

回答

5

你有一個語法錯誤(用Python的說明)。使用:

[element for element in wts if len(element) == 1] 

列表理解必須以for之前的表達式開頭。有了這個語法,你可以申請進一步的操作,如uppercasing例如:

[element.upper() for element in wts if len(element) == 1] 

因爲你要重複迭代變量名那麼多,你會經常看到用短的變量名寫的內涵。我可能會寫,使用x爲:

[x for x in wts if len(x) == 1] 
0

您可以使用列表-COMP:

>>> dts = {'H':'1.00794','He':'4.002602','Li':'6.941','Be':'9.012182','B':'10.811','C':'12.0107','N':'14.0067','O':'15.9994'} 
>>> [(el, weight) for el, weight in dts.iteritems() if len(el) == 1] 
[('C', '12.0107'), ('B', '10.811'), ('N', '14.0067'), ('H', '1.00794'), ('O', '15.9994')] 

或者filter

>>> filter(lambda (k, v): len(k) == 1, dts.iteritems()) 
[('C', '12.0107'), ('B', '10.811'), ('N', '14.0067'), ('H', '1.00794'), ('O', '15.9994')] 
0

既然你被要求「打印僅包含原子符號及其相應權重的字典 ...「我想答案應該使用字典c omprehension如:

>>> print {el: wt for el, wt in wts.iteritems() if len(el) == 1} 
{'H': '1.00794', 'C': '12.0107', 'B': '10.811', 'O': '15.9994', 'N': '14.0067'}