繁体   English   中英

在列表理解中出现错误-python

[英]Getting error in list comprehension - python

出现此代码错误(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]

您错过for a 另外,您应该使用==测试int和字符串是否相等,因为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')]

请参阅清单推导中的文档

问题是表达式的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)%10 == 0来检测a*a是否以0结尾。 由于102的倍数,因此我们甚至可以删除第一张支票。 我们可以检查整数i是否为零而not i (这是True如果i == 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM