What is correct python syntax for this kind of list comprehension?
task: {x*y such that x belongs to S & y is iteration count } where S is some other set something开发者_JAVA技巧 like this:
j=0
[i*j for j++ and i in S]
[s1*1, s2*2, s3*3...]
for your edited question, you want
[i * j for j, i in enumerate(S)]
python doesn't have ++
because it keeps a clear distinction between statements and expressions. use
[(i + 40) * i for i in xrange(60)]
another way to do this is
[i * j for i, j in enumerate(xrange(60), start=40)]
and yet another way is
[i * j for i, j in zip(xrange(40, 100), xrange(60))]
I think that the first is the best way to do it because it reduces function calls and is the most readable.
Also, if you don't know that you absolutely need a list, use a generator expression
((i + 40) * i for i in xrange(60))
This will allow you to process the results one at a time and never store a whole list in memory. You can pass a generator expression to stuff like sum
, max
, min
and most other builtins.
One way to do this would be to use enumerate
in conjunction with range
:
[x * (count + 1) for count, x in enumerate(range(40, 100))]
Look at other answers for (a lot of) other ways to do this :) :)
I'd do it in a generator:
def fooGen(S):
j = 1
for i in S:
yield i * j
J += 1
S = range(40,100)
[i*j for i,j in enumerate(S)]
"""
task: {x*y such that x belongs to S & y is iteration count } where S is some other set
[snip unfortunate introduction of i and j]
[s1*1, s2*2, s3*3...]
"""
a very simple translation:
[x * y for y, x in enumerate(S, start=1)]
or
[x * (y + 1) for y, x in enumerate(S)]
you can use the current element index as an incrementor
>>> S=[2,4,6,8]
>>> [i*(S.index(i)+1) for i in S]
[2, 8, 18, 32]
>>>
so your c-ish "j++" is S.index(i)+1
精彩评论