如何在 python 列表中找到平均值、最大值和最大(类似于 excel 函数)?

我有一个数字列表,我想从这个列表中再创建 3 个列表,其中包含其中的最大值、平均值和第五大数字。我的原始列表overdraw是列表块,这意味着其中有子块,每个块中有 6 个数字,总共有 3 个块或 6x3 矩阵或数组。


overdraw:

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

我知道如何计算此列表中的最大值、平均值和 5 个最大值。但是我想要一个特定的答案,比如我知道每个块的最大值、平均值和第 5 个最大值,但我希望它们被打印 4 次。我知道所有的价值观:


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]

如您所见,每个平均值、最大值和最大数在各自的列表中打印了 4 次。那么任何人都可以帮助这个答案吗?


猛跑小猪
浏览 173回答 2
2回答

慕哥9229398

使用怎么样pandas.DataFrame.explodeimport pandas as pddf = 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            141           24   45            142           24   45            143           24   45            140           36   76            231           36   76            232           36   76            233           36   76            230           34   54            221           34   54            222           34   54            223           34   54            22从这里开始,您仍然可以执行所有您想要的计算和/或获取 NumPy 数组,执行df.values.根据您的评论,您还可以将您的专栏作为单独的实体,例如>>> 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]哪种方法开始有点矫枉过正,但可读性强。

梵蒂冈之花

返回您指定的列表的解决方案import itertoolsimport numpy as npn_times = 4overdraw = [[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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python