繁体   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