【发布时间】:2015-09-21 13:31:07
【问题描述】:
鉴于floats spendList 的列表,我想将round() 应用于每个项目,并使用四舍五入的值更新列表,或创建一个新列表。
我正在想象这种使用列表理解来创建新列表(如果无法覆盖原始列表),但是将每个项目传递给 round() 呢?
我发现序列解包here 所以尝试了:
round(*spendList,2)
得到:
TypeError Traceback (most recent call last)
<ipython-input-289-503a7651d08c> in <module>()
----> 1 round(*spendList)
TypeError: round() takes at most 2 arguments (56 given)
所以推测round 试图对列表中的每个项目进行四舍五入,我尝试了:
[i for i in round(*spendList[i],2)]
得到:
In [293]: [i for i in round(*spendList[i],2)]
File "<ipython-input-293-956fc86bcec0>", line 1
[i for i in round(*spendList[i],2)]
SyntaxError: only named arguments may follow *expression
在这里甚至可以使用序列解包吗?如果没有,如何实现?
【问题讨论】:
-
docs.python.org/2/library/functions.html#map ...或者你说的列表理解
-
@Anentropic 谢谢,工作。我需要添加一个
lambda以允许round()采用的参数:map(lambda x: round(x,2), spendList)。 map 能以某种方式自己处理这些参数吗? -
spendList[:] = [round(1,2) for i in spendList]将更新原始对象,您也可以使用常规 for 循环使用 enumerate -
@Pyderman 是的,您需要像以前那样使用 lambda,或者向函数调用添加静态参数的通用方法是 docs.python.org/2/library/functools.html#functools.partial
标签: python list python-2.7 iteration sequence