如何在用户在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)small = 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的答案