如何在用户在python中提供的2D列表中找到最小,最大值,总和和平均值?

问题描述 投票:-1回答:3

如何在用户在python中提供的2D列表中找到最小,最大值,总和和平均值?

python list 2d
3个回答
2
投票

你可以先把它弄平。

a = [[1, 2], [3, 4]]
flattened = [num for sublist in a for num in sublist]
min_val = min(flattened)
max_val = max(flattened)
sum_val = sum(flattened)
avg_val = sum(flattened) / len(flattened)

所以在你的情况下它将是:

def list_stats(a):
    flattened = [num for sublist in a for num in sublist]
    min_val = min(flattened)
    max_val = max(flattened)
    sum_val = sum(flattened)
    avg_val = sum_val / len(flattened)
    return min_val, max_val, sum_val, avg_val

#Testing
a = [[1.2,3.5],[5.5,4.2]]
small, large, total, average = list_stats(a)

0
投票

这就是我到目前为止:

    a = [[]]
    total = 0
    counter = 0 
    small = a[0][0]
    for i in a: 
        if i > small:
            return True 
            total += i 
            counter += 1 
    average = total / counter
    return small, large, total, average 

#Testing
a = [[1.2,3.5],[5.5,4.2]]
small, large, total, average = list_stats(a)

我得到以下两个错误:小,大,总,平均= list_stats(a)small = a [0] [0] IndexError:列表索引超出范围

函数list_stats未定义。

a = [[]]是一个包含空列表的列表。 a[0][0]是一个不存在的元素。


0
投票

试试这个:

def list_stats(a):
    total = 0
    counter = 0 
    small = 99999
    large = -999
    for x in a:
        for y in x:
            if y < small: 
                small = y
            if y > large:
                large = y
            counter += 1
            total += y
    average = total / counter
    return small, large, total, average 

我更喜欢Eric的答案

© www.soinside.com 2019 - 2024. All rights reserved.