Skip to main content
 首页 » 编程设计

python之如何巧妙地将 Python 列表的每一项传递给函数并更新列表(或创建一个新列表)

2025年05月04日13youxin

给定一个 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 

这里甚至可以使用序列拆包吗?如果没有,如何实现?

请您参考如下方法:

你有你的 list comprehension错误的方法:

[i for i in round(*spendList[i],2)] 

应该是:

[round(i, 2) for i in spendList] 

您想遍历 spendList,并将 round 应用于其中的每个项目。这里不需要 * ("splat") 解包;这通常只需要接受任意数量的位置参数的函数(并且,根据错误消息,round 只需要两个)。