在python中修改一个没有任何循环的大列表 [英] Modify a large list without any loops in python

查看:46
本文介绍了在python中修改一个没有任何循环的大列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的名单是:

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?

更新:这可能是一个很大的列表,大约10000个元素.

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

推荐答案

使用Python的 map 功能

Use Python's map functionality

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

这是上面链接中对map函数的描述:

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

地图(函数,可迭代,...)
将函数应用于每个iterable并返回列表结果.如果传递了其他可迭代参数,则函数必须接受那么多参数,并将其应用于所有项目并行的可迭代对象.如果一个迭代比另一个短假定扩展为无项目.如果函数为None,则假定身份函数;如果有多个参数,则map()返回由包含相应项目的元组组成的列表来自所有可迭代对象(一种转置操作).可迭代的参数可以是序列或任何可迭代的对象;结果是总是一个列表.

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.

这篇关于在python中修改一个没有任何循环的大列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆