如果您使用 Python 版本 >= 3.4,则导入统计模块
from statistics import mean
如果使用较低版本,创建一个函数来计算平均值
def mean(array):
sum = 0
if (not(type(array) == list)):
print("there is some bad format in your input")
else:
for elements in array:
try:
sum = sum + float(elements)
except:
print("non numerical entry found")
average = (sum + 0.0) / len(array)
return average
创建一个列表列表,例如
myList = [[1,2,3],[4,5,6,7,8],[9,10],[11,12,13,14],[15,16,17,18,19,20,21,22],[23]]
遍历我的列表
for i, lists in enumerate(myList):
print(i, mean(lists))
这将打印出序列 n 和第 n 个列表的平均值。
要特别查找仅第 n 个列表的平均值,请创建一个函数
def mean_nth(array, n):
if((type(n) == int) and n >= 1 and type(array) == list):
return mean(myList[n-1])
else:
print("there is some bad format of your input")
请注意,索引从零开始,例如,如果您正在寻找第 5 个列表的平均值,它将位于索引 4。这解释了代码中的 n-1。
然后调用函数,例如
avg_5thList = mean_nth(myList, 5)
print(avg_5thList)
在 myList 上运行上述代码会产生以下结果:
0 2.0
1 6.0
2 9.5
3 12.5
4 18.5
5 23.0
18.5
其中前六行是从迭代循环生成的,并显示第 n 个列表的索引和列表平均值。最后一行 (18.5) 显示了 mean_nth(myList, 5) 调用后第 5 个列表的平均值。
此外,对于像您这样的列表,
a = [
[1, 2, 3],
[2, 3, 4],
[3, 4, 5, 6]
]
假设您想要第一个元素的平均值,即 (1+2+3)/3 = 2,或第二个元素,即 (2+3+4)/3 = 3,或第四个元素,例如 6/ 1 = 6,您将需要找到每个列表的长度,以便您可以识别列表中的第 n 个元素是否存在。为此,您首先需要按照列表长度的顺序排列列表。
你可以
1) 先根据组成列表的大小对主列表进行迭代排序,然后通过排序后的列表判断组成列表是否足够长
2) 或者您可以迭代地查看原始列表以了解组成列表的长度。
(如果需要,我绝对可以重新制定更快的递归算法)
计算上第二个更有效,因此假设您的第 5 个元素在索引 (0, 1, 2, 3, 4) 中表示第 4 个,或第 n 个元素表示第 (n-1) 个元素,让我们继续吧创建一个函数
def find_nth_average(array, n):
if(not(type(n) == int and (int(n) >= 1))):
return "Bad input format for n"
else:
if (not(type(array) == list)):
return "Bad input format for main list"
else:
total = 0
count = 0
for i, elements in enumerate(array):
if(not(type(elements) == list)):
return("non list constituent found at location " + str(i+1))
else:
listLen = len(elements)
if(int(listLen) >= n):
try:
total = total + elements[n-1]
count = count + 1
except:
return ("non numerical entity found in constituent list " + str(i+1))
if(int(count) == 0):
return "No such n-element exists"
else:
average = float(total)/float(count)
return average
现在让我们在你的列表中调用这个函数a
print(find_nth_average(a, 0))
print(find_nth_average(a, 1))
print(find_nth_average(a, 2))
print(find_nth_average(a, 3))
print(find_nth_average(a, 4))
print(find_nth_average(a, 5))
print(find_nth_average(a, 'q'))
print(find_nth_average(a, 2.3))
print(find_nth_average(5, 5))
对应的结果是:
Bad input format for n
2.0
3.0
4.0
6.0
No such n-element exists
Bad input format for n
Bad input format for n
Bad input format for main list
如果你有一个不稳定的列表,比如
a = [[1, 2, 3], 2, [3, 4, 5, 6]]
包含一个非列表元素,你会得到一个输出:
non list constituent found at location 2
如果您的成员名单不稳定,例如:
a = [[1, 'p', 3], [2, 3, 4], [3, 4, 5, 6]]
在列表中包含非数字实体,并通过print(find_nth_average(a, 2))求第二个元素的平均值
你得到一个输出:
non numerical entity found in constituent list 1