# 如何在 python 列表中找到平均值、最大值和最大（类似于 excel 函数）？

2023-01-04 16:43:56

overdraw:

[[16,13,23,14,33,45],[23,11,54,34,23,76],[22,54,34,43,41,11]]

Max = [45, 76, 54]

Average = [24, 37, 34]

Largest(5th) = [14, 23, 22]

overdraw = [[16,13,23,14,33,45],[23,11,54,34,23,76],[22,54,34,43,41,11]]

x = [sorted(block, reverse=True) for block in overdraw] # first sort the whole list

max = [x[i][0] for i in range(0, len(x))] # for max

largest = [x[i][4] for i in range(0, len(x))] #5th largest

average = [sum(x[i])/len(x[i]) for i in range(0, len(x))] #average

print("max: ", max)

print("5th largest: ", largest)

print("average: ", average)

Average = [24, 24, 24, 24, 37, 37, 37, 37, 34, 34, 34, 34]

Max = [45, 45, 45, 45, 76, 76, 76, 76, 54, 54, 54, 54]

Largest(5th) = [14, 14, 14, 14, 23, 23, 23, 23, 22, 22, 22, 22]

## 2 回答

TA贡献1630条经验 获得超5个赞

import pandas as pd

df = pd.DataFrame({

'OvIdx'       : 3 * [range(4)],

'Average'     : average,

'Max'         : max,  # should be renamed/assigned as max_ instead

'Largest(5th)': largest

}).explode('OvIdx').set_index('OvIdx').astype(int)

print(df)

Average  Max  Largest(5th)

OvIdx

0           24   45            14

1           24   45            14

2           24   45            14

3           24   45            14

0           36   76            23

1           36   76            23

2           36   76            23

3           36   76            23

0           34   54            22

1           34   54            22

2           34   54            22

3           34   54            22

>>> df.Average.tolist()

[24, 24, 24, 24, 36, 36, 36, 36, 34, 34, 34, 34]

>>> df.Max.tolist()

[45, 45, 45, 45, 76, 76, 76, 76, 54, 54, 54, 54]

>>> df['Largest(5th)'].tolist()  # as string key since the name is a little bit exotic

[14, 14, 14, 14, 23, 23, 23, 23, 22, 22, 22, 22]

TA贡献1618条经验 获得超5个赞

import itertools

import numpy as np

n_times = 4

overdraw = [[16,13,23,14,33,45],[23,11,54,34,23,76],[22,54,34,43,41,11]]

y = [sorted(block, reverse=True) for block in overdraw]

maximum = list(itertools.chain(*[[max(x)]*n_times for x in y]))

average = list(itertools.chain(*[[int(round(sum(x)/len(x)))]*n_times for x in y]))

fifth_largest = list(itertools.chain(*[[x[4]]*n_times for x in y]))

print(f"Average = {average}")

print(f"Max = {maximum}")

print(f"Largest(5th): {fifth_largest}")

Average = [24, 24, 24, 24, 37, 37, 37, 37, 34, 34, 34, 34]

Max = [45, 45, 45, 45, 76, 76, 76, 76, 54, 54, 54, 54]

Largest(5th): [14, 14, 14, 14, 23, 23, 23, 23, 22, 22, 22, 22]

• 2 回答
• 0 关注
• 13 浏览

0/150