获取列表时出错

2024-04-25 19:45:17 发布

您现在位置: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]

Tags: and代码in列表ifis错误语法
2条回答

问题是表达式的产量部分:

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的倍数,所以我们甚至可以删除第一个检查。我们可以用not i(这是Truei == 0)检查整数i是否为零。你知道吗

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

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]

您缺少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')]

参见docs on list comprehensions。你知道吗

相关问题 更多 >