簡體   English   中英

嘗試使用列表理解來過濾字典

[英]Trying to filter a dictionary using list comprehension

使用單個語句,打印僅包含原子符號及其在wts(我的詞典)中那些原子符號中只有一個字母的元素的相應權重的字典。 即,包括“ H”,但省略“ He”。 我的字典設置為{'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

您有語法錯誤(如Python所述)。 采用:

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

列表理解必須以for之前的表達式開頭。 使用此語法,您可以應用進一步的操作,例如大寫:

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

因為您必須重復很多次迭代變量名,所以您經常會看到用簡短的變量名寫的理解。 我可能會使用x編寫為:

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

您可以使用list-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')]

由於系統要求您“僅打印包含原子符號及其相應權重的字典...”,我認為答案應使用字典理解,如:

>>> 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'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM