【问题标题】:How to neatly pass each item of a Python list to a function and update the list (or create a new one)如何巧妙地将 Python 列表的每个项目传递给函数并更新列表(或创建新列表)
【发布时间】: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

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

【问题讨论】:

标签: python list python-2.7 iteration sequence


【解决方案1】:

你的list comprehension 搞错了:

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

应该是:

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

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

【讨论】:

  • 最优雅的解决方案。以前从未考虑过使用函数调用来开始列表理解。不错。
【解决方案2】:

您可以为此使用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 返回的是迭代器而不是列表。

【讨论】:

  • 请注意,根据the introduction of the map iterator(强调我的):“快速解决方法是将map() 包装在list() 中,例如list(map(...))但更好的解决方法通常是使用列表推导"
  • 特别是,如果您使用带有map 的lambda,那么列表推导可能更具可读性。 [round(x,2) for x in lst]
  • @Anand 我刚刚发现我需要lamdba 或类似的东西来允许舍入;你只是打败了我添加我的评论。谢谢。
【解决方案3】:

你仍然可以使用你刚才谈到的列表推导,只是这样:

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]

【讨论】:

    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多