Comprehension with two variables - explanation needed
webmailgroups at gmail.com
Sun Nov 23 15:56:55 CET 2014
I would like to ask you for some explanations on comprehensions. (Don't be
scared, it just some particular example ^_^)
I found this little "find prime number" example over the internet:
>>> 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]
It looked pretty clear to me, till the time I decided to make some changes
to it %)))
Ok this is the case:
As you can see the first line's comprehension produces a list, that includes
all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i).
So I get this pattern: noprimes = = [4, 6, 8...48, 6, 9,12.. ].
The change that I tried to apply to this comprehension would lead to the
following pattern: noprimes = = [[4, 6,8.48], [6, 9, 12..], ..,[some
But despite my struggling on it for the whole day, I haven't got to the
desirable result(using comprehensions only)
Please, don't get me wrong, I'm not a lazy one (just a beginner).
In my case, I made some googling, and found some patterns for matrices,
that look this one(for example):
Matrix = [[0 for x in range(5)] for x in range(5)]
But when I tried to use square brackets with my code, it yields an error
about definition of "i", for instance:
File "<pyshell#30>", line 1, in <module>
noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]
NameError: name 'i' is not defined.
Then I tried to apply those brackets to "j", like this:
>>> noprimes = [[j] for i in range(2, 8) for j in range(i*2, 50, i)]
In this case I get, pretty predictable result, like this: [[num], [num],
[num],...,[num]], and this is still not what I'm looking for..
So I moved further, and succeeded to solve my problem in a different manner:
>>> for i in range(2,8):
Which yields, in fact, the matrix I wanted from the beginning:
noprimes == [[4, 6, 8, 10, 12,.., 48], [6, 9, 12, 15, 18, ., 42, 45,
Yep, this the "classical" way for me, on the other hand I have the feeling,
that this is not, the ultimate solution. ^_^
So my questions is still persists:
1) Is it possible to realize such a thing by applying changes only to
initial comprehension? If yes, it would be nice to see the solution.
2) How actually bad is my solution? I mean, after all, there are nested
functions call in my code, so how much the speed is affected(if any)?
Thanks a lot in advance,
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list