简体   繁体   中英

Python list comprehension - syntax error on "if" statement

I consider myself to be an intermediate on Python so it's bothering me that I cannot work out why I am having the following problem.

I am using the SQLAlchemy module. Within the table object there is a column object which is a collection:

table.columns
# <sqlalchemy.sql.base.ImmutableColumnCollection object>

Using a list comprehension, I can see the data types of all of these columns:

[x.type for x in user.columns]
# [Integer(), String(length=16), String(length=60), String(length=50)]

However, the second I put an "if" statement at the end, the statement fails with a syntax error:

[x.type for x in user.columns if x.type = 'Integer()']
#   File "<stdin>", line 1
#   [x.type for x in user.columns if x.type = 'Integer()']
#                                            ^
# SyntaxError: invalid syntax

What I want to know is - why? Why can I return x.type in my output but I can't use it to filter?

This should work:

 [x.type for x in user.columns if x.type == 'Integer()']

because the if needs an operator of equality:

 ==

and not an assignement.

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