在列表理解中获得错误 - python

时间:2018-01-05 09:31:20

标签: python python-3.x list list-comprehension

使用此代码时出错 (SyntaxError:语法无效)

score = [a*a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']
print(score)

结果:

SyntaxError: invalid syntax

但是当我使用它而没有列表理解方法时,相同的代码工作正常。

score = []
for a in range(1,100):
    if (a*a)%2 is 0 and str(a*a)[-1] is '0':
        score.append(a*a)
print(score)

结果:

[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]

2 个答案:

答案 0 :(得分:8)

您错过了for a。此外,您应该使用==来测试整数和字符串的相等性,因为is会检查对象标识:

score = [a*a for a in range(1, 100) if (a*a) % 2 == 0 and str(a*a)[-1] == '0']

您还可以将== 0缩短为bool项检查,并且通常会考虑使用endswith进行更强大的后缀检查:

score = [a*a for a in range(1, 100) if not (a*a) % 2 and str(a*a).endswith('0')]

请参阅docs on list comprehensions

答案 1 :(得分:5)

问题是表达式的 yield 部分:

score = [a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']

您想将a*a添加到列表中,所以:

score = [a*a for a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']

但代码非常优雅。您使用引用相等的is。虽然大多数解释器缓存字符和小整数,但依赖它会有点风险:程序工作必须满足的假设越多,就越容易出错。

此外,您可以通过选中a*a来检测0是否以(a*a)%10 == 0结尾。由于102的倍数,我们甚至可以放弃第一次检查。我们可以使用i检查整数not i为零(Truei == 0)。

因此,更安全,更短的解决方案是:

score = [a*a for a in range(1, 100) if not (a * a) % 10]

然后产生:

>>> [a*a for a in range(1, 100) if not (a * a) % 10]
[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]