Modify a large list without any loops in python

戏子无情 提交于 2021-02-08 13:14:17

问题


My list is:

a=[1,2,3,4]

Now I want my list to be:

a=[-1,-2,-3,-4]

How can I change my list this way without using any loops?

Update: this may be a large list, on the order of 10000 elements.


回答1:


Use Python's map functionality

a[:] = map(lambda x: -x, a)

Here's the description of the map function from the above link:

map(function, iterable, ...)
Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.




回答2:


some quick and dirty benchmarks from ipython

In [1]: a=range(10000)

In [2]: import numpy 

In [3]: timeit [-i for i in a]
1000 loops, best of 3: 576 us per loop

In [4]: timeit map(lambda i:-i, a)
1000 loops, best of 3: 1.68 ms per loop

In [5]: timeit list(-1*numpy.array(a))
100 loops, best of 3: 2.53 ms per loop

Note that if a can be a numpy array you don't need to wast time on the conversion

In [6]: a = numpy.array(a)

In [7]: timeit -- -a
100000 loops, best of 3: 15.4 us per loop



回答3:


You can use the numpy library:

list(-1*numpy.array(a))



回答4:


import operator
a = map(operator.neg, a)



回答5:


Well it depends on what you mean by without any loops. In case you just want to avoid explicit loops like

a = [ -x for x in a ]

you could use the map function, that would loop for you.

a = map( lambda x:-x, a)



回答6:


You cannot do it without loop but you can hide the fact.

map(lambda x: -x, a)



回答7:


Without knowing the exact reason why loop is not required and knowing that there is no other efficient way to negate a list here is my super fast solution (I have no knowledge of the context so this may not work)

class nlist(object):
    def __init__(self, l):
        self._list = l

    def __getitem__(self, key):
        return -self._list[key]

    def __iter__(self):
        for i in self._list:
            yield -i


nl = nlist([1,2,3,4])
for i in nl:
    print i



回答8:


a = [-a[0], -a[1], -a[2], -a[3]]

Now the problem is that this only works if a has exactly 4 items. To generalise to different number of items...well that's what loops are for.



来源:https://stackoverflow.com/questions/8437024/modify-a-large-list-without-any-loops-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!