简体   繁体   中英

Explanation of syntax in for loop?

I was trying to do some of the problems on projecteuler, and I got to the one with the sum of squares and squares of sums. I didn't want to brute force it, so I looked up the solution, which was:

sum1 = 0
sum2 = 0

for i in ((x,x ** 2) for x in range(1,100+1)):
    sum1 += i[0]
    sum2 += i[-1]

print(sum1 ** 2 - sum2)

I do not get:

(x,x ** 2) for x in range(1,100+1)

I've seen this in another code golf solution in javascript too. Is this a specific syntax, or an unfamiliar way of something regular? Can someone please explain?

When confronted with complex syntax, add print statements.

for i in ((x,x ** 2) for x in range(1,100+1)):
    print i

Not too helpful.

Try this.

a = ((x,x ** 2) for x in range(1,100+1))
print a
for i in a:
     print i

Helpful? Maybe.

Try this:

a = ((x,x ** 2) for x in range(1,100+1))
b = list(a)
print b

Hmmm. The for i in a loop stops working, also. This generator object seems to do it's thing once only. Either in a for loop or in the list() (or tuple() ) function but not both.

Try this.

 for x in range(1,100+1): 
      print x, x**2

Okay. So, what have we learned?

((x,x ** 2) for x in range(1,100+1)) is a generator expression. http://www.python.org/dev/peps/pep-0289/

It's "iterable" and can be used in a for statement or the list() function.

Also, we've learned to add print statements to explore confusing syntax.

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