繁体   English   中英

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

[英]How do I find the smallest, largest value and total and the average in a 2D list that the user provides in python?

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

您可以先将其展平。

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)

这是我到目前为止所拥有的:

    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)小= a [0] [0] IndexError:列表索引超出范围

未定义函数list_stats

a = [[]]是包含空列表的列表。 a[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的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM