如何在用户在python中提供的2D列表中找到最小,最大值和总数以及平均值?
You can flatten it first.
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)
So in your case it'll be:
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)
This what I have so far:
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)
I'm getting the following two errors: small, large, total, average = list_stats(a) small = a[0][0] IndexError: list index out of range
The function list_stats
is not defined.
a = [[]]
is a list that contains an empty list. a[0][0]
is an element that does not exist.
try this:
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
I like Eric's answer better
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.