简体   繁体   中英

Getting error in list comprehension - python

Getting an error with this code (SyntaxError: invalid syntax)

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 . Also, you should use == to test ints and strings for equality because is checks object identity:

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:

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:

score = [ 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:

score = [ 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. 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 . Since 10 is a multiple of 2 , we can even drop the first check then. We can check for an integer i being zero with not i (this is True is i == 0 ).

So a more safe and shorter solution is:

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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