[英]Getting error in list comprehension - python
Getting an error with this code (SyntaxError: invalid syntax) 出现此代码错误(SyntaxError:语法无效)
score = [a*a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']
print(score)
Result: 结果:
SyntaxError: invalid syntax
but same code working fine when i use it without list comprehension method. 但是当我使用没有列表理解方法的代码时,相同的代码工作正常。
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)
result: 结果:
[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]
You are missing the for a
. 您错过
for a
。 Also, you should use ==
to test ints and strings for equality because is
checks object identity: 另外,您应该使用
==
测试int和字符串是否相等,因为is
检查对象身份:
score = [a*a for a in range(1, 100) if (a*a) % 2 == 0 and str(a*a)[-1] == '0']
You could also shorten the == 0
to a bool
check and generally consider to use endswith
for more robust suffix checking: 您也可以将
== 0
缩短为bool
检查,通常考虑使用endswith
进行更可靠的后缀检查:
score = [a*a for a in range(1, 100) if not (a*a) % 2 and str(a*a).endswith('0')]
See the docs on list comprehensions . 请参阅清单推导中的文档 。
The problem is the yield part of the expression: 问题是表达式的yield部分:
score = [
a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']
You want to add a*a
to the list, so: 您想要将
a*a
添加到列表中,因此:
score = [
a*a for a in range(1, 100) if (a*a)%2 is 0 and str(a*a)[-1] is '0']
But the code is very inelegantly. 但是代码非常笨拙。 You use
is
which is reference equality. 您使用
is
是引用相等。 Although most interpreters cache characters, and small integers, it is a bit risky to rely on it: the more assumptions that have to be satisfied for a program to work, the more can go wrong. 尽管大多数解释器会缓存字符和较小的整数,但是依赖于它会有点冒险:要使程序正常运行,必须满足的假设越多,出错的可能性就越大。
Furthermore you can detect whether a*a
will end with 0
, by checking (a*a)%10 == 0
. 此外,可以通过检查
(a*a)%10 == 0
来检测a*a
是否以0
结尾。 Since 10
is a multiple of 2
, we can even drop the first check then. 由于
10
是2
的倍数,因此我们甚至可以删除第一张支票。 We can check for an integer i
being zero with not i
(this is True
is i == 0
). 我们可以检查整数
i
是否为零而not i
(这是True
如果i == 0
)。
So a more safe and shorter solution is: 因此,更安全,更短的解决方案是:
score = [a*a for a in range(1, 100) if
not (a * a) % 10]
This then produces then: 然后产生:
>>> [a*a for a in range(1, 100) if not (a * a) % 10]
[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.