You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何对二维数组的数值进行四舍五入取整?

Fixing 2D Array Rounding in Python

Hey there! Let's sort out that rounding issue with your 2D array. The problem in your original code is that you're trying to apply round() to an entire sublist (P[i]) instead of each individual element inside the sublist. round() only works on single numeric values, not lists—so that's why you ran into errors.

Why Your Original Code Failed

Your line P[i] = int(round(P[i], 0)) tries to round the whole sublist (like [3.2, 3.7, 2.1]) at once, which Python doesn't allow. You need to iterate through each number in every sublist to apply the rounding logic correctly.

Solution 1: Nested Loops (Explicit & Easy to Follow)

If you prefer a straightforward, readable approach, use nested loops to go through each sublist and then each element inside it:

P = [[3.2, 3.7, 2.1], [4.5, 2.1, 2.3], [3.1, 2.5]]

for i in range(len(P)):
    rounded_sublist = []
    for num in P[i]:
        # Use int(num + 0.5) here to get traditional 0.5-up rounding (matches your expected output)
        rounded_num = int(num + 0.5)
        rounded_sublist.append(rounded_num)
    P[i] = rounded_sublist

print(P)  # Output: [[3, 4, 2], [5, 2, 2], [3, 3]]

Solution 2: List Comprehension (Pythonic & Concise)

For a cleaner, more idiomatic Python solution, use a nested list comprehension to process all elements in one line:

P = [[3.2, 3.7, 2.1], [4.5, 2.1, 2.3], [3.1, 2.5]]

# Nested comprehension to round each element with traditional 0.5-up logic
P = [[int(num + 0.5) for num in sublist] for sublist in P]

print(P)  # Output: [[3, 4, 2], [5, 2, 2], [3, 3]]

Quick Note on Rounding Behavior

Python's built-in round() uses bankers rounding, which rounds numbers ending in 0.5 to the nearest even integer (e.g., round(4.5) becomes 4, round(2.5) becomes 2). Since your expected output wants 4.5 → 5 and 2.5 → 3, using int(num + 0.5) (for positive numbers) gives you that classic "round up on 0.5" behavior you need.

内容的提问来源于stack exchange,提问作者cavezonk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:32:37