Python 如何在列表循环中找到特定位置的最小值和最大值?
这就是我到目前为止所做的:Python 如何在列表循环中找到特定位置的最小值和最大值?,python,python-3.x,Python,Python 3.x,这就是我到目前为止所做的: import random list1 = [] list2 = [] for i in range(5): for j in range(3): list1.append(random.randrange(1,101)) list2.append(list1) list1=[] for i in list2: for j in i: print(j, end=",") print(" (S
import random
list1 = []
list2 = []
for i in range(5):
for j in range(3):
list1.append(random.randrange(1,101))
list2.append(list1)
list1=[]
for i in list2:
for j in i:
print(j, end=",")
print(" (Sum: ", sum(i), " Average: ", (sum(i)/len(i)), ")", sep="")
print()
我希望能够在每列中找到最大和最小的数字。例如,输出为:
1,91,46, (Sum: 138 Average: 46.0)
82,62,21, (Sum: 165 Average: 55.0)
39,52,41, (Sum: 132 Average: 44.0)
60,69,45, (Sum: 174 Average: 58.0)
20,21,7, (Sum: 48 Average: 16.0)
Largest number of first column: 82 Smallest number of first column: 1
Largest number of second column: 91 Smallest number of second column: 21
Largest number of third column: 46 Smallest number of third column: 7
我知道最小值/最大值,有什么方法可以使用它们来获得这些结果吗?还是我必须使用不同的方法?感谢您的帮助 最简单的方法如下:
col1 = []
col2 = []
col3 = []
for i in list2:
col1.append(i[0])
col2.append(i[1])
col3.append(i[2])
print("Largest number of first column:", max(col1), ",Smallest number of first column:", min(col1) )
print("Largest number of second column:", max(col2), ",Smallest number of second column:", min(col2) )
print("Largest number of third column:", max(col3), ",Smallest number of third column:", min(col3) )
您可以使用zip(*行)
样本输出:
(5, 22, 95) sum: 122 avg: 40 min: 5 max: 95
(92, 88, 67) sum: 247 avg: 82 min: 67 max: 92
(97, 61, 3) sum: 161 avg: 53 min: 3 max: 97
(95, 37, 67) sum: 199 avg: 66 min: 37 max: 95
(47, 13, 29) sum: 89 avg: 29 min: 13 max: 47
如果使用的是numpy,则可以使用而不是嵌套列表。使用array.T
(转置)迭代列而不是行
for column in numpy.array(rows).T:
print(column, column.sum(), column.mean(dtype=int), column.min(), column.max())
[ 5 22 95] 122 40 5 95
[92 88 67] 247 82 67 92
[97 61 3] 161 53 3 97
[95 37 67] 199 66 37 95
[47 13 29] 89 29 13 47
如果可以将列表组织为二维数组,则可以使用numpy数组操作(求和、平均值…)是否尝试使用列表的
列表
?您是否计划从上面显示的示例中获得一个5x3
矩阵?为了获得良好的顺序,没有“二维列表”的概念[这是numpy
或数组术语]。您拥有的是一个列表列表(不需要与int
数组中的列表长度相同)。但是zip
是一条出路+1.
for column in numpy.array(rows).T:
print(column, column.sum(), column.mean(dtype=int), column.min(), column.max())
[ 5 22 95] 122 40 5 95
[92 88 67] 247 82 67 92
[97 61 3] 161 53 3 97
[95 37 67] 199 66 37 95
[47 13 29] 89 29 13 47