简体   繁体   中英

Syntax error from list comprehension with a conditional

I am using a library (pymatgen) in which a enum Orbital is defined. Each element can be defined as an OrbitalType. There are several flavors of orbital types which are defined by the letters s, p, d, and f. The following code works fine.

In [35]: myorbitals = []
In [36]: for orbital in Orbital:
   ....:     if orbital.orbital_type == OrbitalType.d:
   ....:         myorbitals.append(orbital)
   ....:       

In [37]: myorbitals
Out[37]:  [<Orbital.dxy: 4>,  <Orbital.dyz: 5>, 
<Orbital.dz2: 6>,  <Orbital.dxz: 7>,  <Orbital.dx2: 8>]

My question is, why do I get a syntax error when I attempt to do the same thing to construct myarray using a list comprehension?

In [38]: myarray = [orbital if orbital.orbital_type == OrbitalType.d for orbital in Orbital]

  File "<ipython-input-38-a770dfff8a02>", line 1
    myarray = [orbital if orbital.orbital_type == OrbitalType.d for orbital in Orbital]
                                                                  ^
SyntaxError: invalid syntax

正确的语法应为:

myarray = [orbital for orbital in Orbital if orbital.orbital_type == OrbitalType.d]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM