English 中文(简体)
Would it be very unpythonic to use this setitem function to overcome the list comprehension limitation?
原标题:
>>> a=range(5)
>>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
[0, 2, 4]
>>> a
[0, 1, 2, 3, 4]
>>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment
SyntaxError: invalid syntax
>>> def setitem(listtochange,n,value):  ## function to overcome limitation
    listtochange[n]=value
    return value

>>> [setitem(a,i, x ) for i in range(0,len(a),2)] ## proving the function
[ x ,  x ,  x ]
>>> a 
[ x , 1,  x , 3,  x ]   # We did assignment anyway
最佳回答

For my timing mentioned (see also the Improving pure Python prime sieve by recurrence formula) from time import clock

def rwh_primes1(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

def rwh_primes_tjv(n):
    # recurrence formula for length by amount1 and amount2 tjv
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    amount1 = n-10
    amount2 = 6

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
             ## can you make recurrence formula for whole reciprocal?
            sieve[i*i//2::i] = [False] * (amount1//amount2+1)
        amount1-=4*i+4
        amount2+=4

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_len(n):
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * len(sieve[i*i//2::i])

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]

def rwh_primes_any(n):
    """ Returns  a list of primes < n """
    halfn=n//2
    sieve = [True] * (halfn)

    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            any(sieve.__setitem__(item,False) for item in range(i*i//2,halfn,i))

    return [2] + [2*i+1 for i in xrange(1,n//2) if sieve[i]]


if __name__ == "__main__":
    n = 1000000

    print("rwh sieve1")
    t=clock()
    r=rwh_primes1(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with recurrence formula")
    t=clock()
    r=rwh_primes_tjv(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with len function")
    t=clock()
    r=rwh_primes_len(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))

    print("rwh sieve with any with side effects")
    t=clock()
    r=rwh_primes_any(n)
    print("Length %i,  %s ms" %(len(r),1000*(clock()-t)))
    raw_input( Ready )

""" Output:
rwh sieve1
Length 78498,  213.199442946 ms
rwh sieve with recurrence formula
Length 78498,  218.34143725 ms
rwh sieve with len function
Length 78498,  257.80008353 ms
rwh sieve with any with side effects
Length 78498,  829.977273648 ms
Ready
"""

Length function and all with setitem are not satisfactory alternatives, but the timings are here to demonstrate it.

rwh sieve with len function Length 78498, 257.80008353 ms

rwh sieve with any with side effects Length 78498, 829.977273648 ms

问题回答

Don t use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead:

for i in range(0,len(a),2):
    a[i] = 3

Apart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and completely unnecessary here.

Yes. And I recommend using

a[::2] = [ x ] * len(a[::2])

instead.


Edit:

Microbenchmarks for Python 2.6:

~:249$ python2.6 -m timeit -s  a = range(2000)   a[::2] = [8] * len(a[::2]) 
10000 loops, best of 3: 26.2 usec per loop

~:250$ python2.6 -m timeit -s  a = range(2000)   a[::2] = [8] * (len(a)/2) 
10000 loops, best of 3: 19.6 usec per loop

~:251$ python2.6 -m timeit -s  a = range(2000)   for i in xrange(0,len(a),2): a[i] = 8 
10000 loops, best of 3: 92.1 usec per loop

~:252$ python2.6 -m timeit -s  a = range(2000)
> def assign(x,i,v):x[i]=v;return v   [assign(a,i,8) for i in xrange(0, len(a), 2)] 
1000 loops, best of 3: 336 usec per loop

Python 3.1:

~:253$ python3.1 -m timeit -s  a = list(range(2000))   a[::2] = [8] * len(a[::2]) 
100000 loops, best of 3: 19.8 usec per loop

~:254$ python3.1 -m timeit -s  a = list(range(2000))   a[::2] = [8] * (len(a)//2) 
100000 loops, best of 3: 13.4 usec per loop

~:255$ python3.1 -m timeit -s  a = list(range(2000))   for i in range(0,len(a),2): a[i] = 8 
10000 loops, best of 3: 119 usec per loop

~:256$ python3.1 -m timeit -s  a = list(range(2000))
> def assign(x,i,v):x[i]=v;return v   [assign(a,i,8) for i in range(0, len(a), 2)] 
1000 loops, best of 3: 361 usec per loop

You can also use list.__setitem__

a = range(5)
[a.__setitem__(i,"x") for i in range(0,len(a),2)]

Or if you want to avoid the contruction of an intermediate list:

any(a.__setitem__(i,"x") for i in range(0,len(a),2))

But assignment in list comprehensions is indeed unpythonic.





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签