简体   繁体   中英

No Primes list Comprehension

Trying to get my head around list comprehensions, and dealing with list in list operations in python.

From this guide http://www.secnetix.de/olli/Python/list_comprehensions.hawk I cannot quite figure out what is happening in the first line.

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

So I have put the line into pythontutor to visualize it. So I can see that for each value of i , j it goes (2,4) (2,6) (2, 8) then (3,6) (3, 9) (3, 12) etc But I cannot understand in a sentence exactly what is happening.

Getting list to work for me is my big stumbling block in getting highly useful, I just can't get it to gel, it's just not "reading" clearly to me.

The line

noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

is equivalent to:

noprimes = []
for i in range(2,8):
   for j in range(i*2, 50, i):
     noprimes.append(j)

and the line

primes = [x for x in range(2, 50) if x not in noprimes]

is equivalent to:

primes=[]
for x in range(2,50): 
  if x not in noprimes: 
    primes.append(x)

Update, in response to comment

The lines

   for j in range(i*2, 50, i):
     noprimes.append(j)

generate a sequence of numbers. The starting number is 2*i , the increment is i , and the sequence stops before it reaches or exceeds 50 .

When i = 2 , it generates the sequence of numbers 4 6 8 ... 48

When i = 3 , it generates the sequence of numbers 6 9 12 ... 48

etc.

The entire loop generates the following numbers

4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48,
6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48,
8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48,
10, 15, 20, 25, 30, 35, 40, 45,
12, 18, 24, 30, 36, 42, 48,
14, 21, 28, 35, 42, 49
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]

This is equivalent to the following:

noprimes = []
for i in range(2, 8):
    for j in range(i*2, 50, i):
        noprimes.append(j)

First it constructs noprimes , which is a list of composite numbers. i ranges from 2 to 7. When i is 2, j iterates through 4, 6, 8, etc.; multiples of 2, but excluding 2. When i is 3, j is 6, 9, 12, etc. So noprimes ends up containing all the composite numbers up to 49 (some of them, multiple times).

Then primes just takes all the numbers from 2 to 49 that aren't in noprimes .

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