如何对列表中的每个元素进行四舍五入?

3

我的意图是获取[[1.23,2.45],[2.35,9.87])。下面的代码只返回一个元素1.23,为什么会这样?

b =[[1.234,2.454],[2.352,9.873]]

def get_round(x):
    for i in x:
        if type(i) ==list:
            for each_i in i: 
                return round(each_i,2)
        else:
            return round(i,2)

get_round(b)   

如何对每个元素进行四舍五入,而不改变现有的数据结构?


1
return 语句在执行时立即退出函数... - undefined
1个回答

4

这里有一种很好的Python方式来做到这一点

func = lambda x: round(x,2)

b =[[1.234,2.454],[2.352,9.873]]
b = [list(map(func, i)) for i in b]
print(b)

[[1.23, 2.45], [2.35, 9.87]]

这将创建一个临时函数,该函数将单个值四舍五入到2位小数。我们称此函数为func。现在,我们想将此函数应用于列表中的每个列表,因此我们遍历外部列表并提取其中的每个列表。然后,我们使用map函数将func应用于此列表中的每个元素。接下来,我们将映射迭代对象转换为列表,就得到了我们的答案。


按照您的方式做事

b =[[1.234,2.454],[2.352,9.873]]

def get_round(x):
    temp = []
    for i in x:
        if type(i) ==list:
            x = []
            for each_i in i: 
                x.append(round(each_i,2))
            temp.append(x)
        else:
            temp.append(round(i,2))
    return temp

print(get_round(b))

在您原始的代码中,您返回得太早了。您找到了列表中的第一个数字,将其转换,然后返回它。这会回到我们从函数调用的地方。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接