簡體   English   中英

Python列表理解-“if”語句上的語法錯誤

[英]Python list comprehension - syntax error on "if" statement

我認為自己是 Python 的中間人,所以我無法弄清楚為什么會遇到以下問題,這讓我很困擾。

我正在使用 SQLAlchemy 模塊。 table對象中有一個column對象,它是一個集合:

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

使用列表推導,我可以看到所有這些列的數據類型:

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

但是,第二次我在末尾添加了“if”語句,該語句失敗並出現語法錯誤:

[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

我想知道的是——為什么? 為什么我可以在輸出中返回x.type但我不能用它來過濾?

這應該有效:

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

因為if需要一個相等的運算符:

 ==

而不是分配。

暫無
暫無

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

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