[英]How to neatly pass each item of a Python list to a function and update the list (or create a new one)
给定一个floats
花单列表List ,我想将round()
应用于每个项目,并使用取整后的值在适当的位置更新列表,或创建一个新列表。
我正在想象使用列表理解来创建新列表(如果无法覆盖原始列表),但是将每个项目传递给round()
呢?
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
甚至可以在这里使用序列拆包吗? 如果没有,如何实现?
您对清单的理解有误:
[i for i in round(*spendList[i],2)]
应该:
[round(i, 2) for i in spendList]
您要遍历spendList
,并将其round
到其中的每个项目。 这里不需要*
( “ splat” )打包; 通常只需要带有任意数量的位置参数的函数(并且根据错误消息, round
仅需要两个)。
您可以为此使用map()
函数-
>>> lst = [1.43223, 1.232 , 5.4343, 4.3233]
>>> lst1 = map(lambda x: round(x,2) , lst)
>>> lst1
[1.43, 1.23, 5.43, 4.32]
对于Python 3.x,您需要使用list(map(...))
因为在Python 3.x中map
返回的是迭代器而不是列表。
您仍然可以这样使用列表理解功能:
list = [1.1234, 4.556567645, 6.756756756, 8.45345345]
new_list = [round(i, 2) for i in list]
new_list将是:[1.12、4.56、6.76、8.45]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.