简体   繁体   中英

Python SyntaxError when creating a list using a generator

I'm relatively new to Python and I'm just trying to get to grips with some of the common features.

I tried to write a simple script to get all the whole number square roots of numbers between 0 and 100. This is what I came up with:

mylist = [n for n*n in xrange(0,101)]

I got a SyntaxError when I ran it, and as far as I can tell, it's not liking the "n for n*n in" bit. Am I right in deducing that this is just not possible? Is there a way to achieve this, or do I need a sqrt() function?

Thanks

You need math.sqrt for something like this.

mylist = [math.sqrt(n) for n in xrange(0,101)]

Python isn't smart enough to see n*n = something and deduce that n = math.sqrt(something) . It's a good thing too -- Who's to say that it shouldn't be n = -math.sqrt(something) ?

Alternatively, you could try the builtin map :

mylist = map(math.sqrt,xrange(0,101))

Although most prefer the list comprehensions these days.

Sometimes, these things can be re-written a little nicer into generator expressions:

def square_less_than(n):
    i = 0
    while True:
       if i*i < n:
          yield i
          i += 1
       else:
          break

print list(square_less_than(10))

Or, the equivalent 1-liner using the excellent itertools module in the standard library:

import itertools
print list(itertools.takewhile(lambda i:i*i < 10,itertools.count()))

The syntax of your list comprehension is incorrect. You can write something like:

import math
mylist = [math.sqrt(n) for n in xrange(0, 101)]

您也可以尝试:

mylist = [n*n for n in xrange(0,101)]

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