0

attrslisttuples或实际上是任何东西的列表)

所以当我运行这段代码时,

if "gold" in s for s in attrs:
    print "something"

它返回

SyntaxError: invalid syntax

我的语法错误是什么?

4

4 回答 4

3

你不能在那里使用genex。

if any('gold' in s for s in attrs):
于 2013-11-06T19:14:58.983 回答
1

你不能像那样放置一个for循环。这不是 Python 语法的工作方式。

也许你的意思是:

for s in attrs:             # For each attribute...
    if "gold" in s:         # ...if "gold" is in it...
        print "something"   # ...print the message.

或者这个:

if any("gold" in s for s in attrs):  # If any of the attributes have "gold"...
    print "something"                # ...print the message.

我认为问题在于您看到了list comprehensiongenerator expression,两者都有相似的语法。但是,这些只有在它们被正确封装(即在[]or中())时才有效。

于 2013-11-06T19:15:09.030 回答
1

这看起来更好:

if "gold" in s:
    for s in attrs:
        print "something"

虽然我真的不确定这将如何工作。你确定你不想要:

for s in attrs:
    if "gold" in s:
        print "something"

从高尔夫的角度来看,我知道单线解决方案更好,但这可能更容易阅读

于 2013-11-06T19:15:18.860 回答
0

您可以执行以下操作:

if "gold" in (x for x in attrs):
    print "something"

如同:

 gen = (x for x in attrs):

 if "gold" in gen:
    print "something"
于 2013-11-06T19:18:11.750 回答