【发布时间】:2012-10-22 03:29:18
【问题描述】:
我们基本上有一个很大的 xcel 文件,我想做的是创建一个列表,其中包含每列的最大值和最小值。有 13 列,这就是为什么 while 循环在达到 14 时应该停止的原因。问题是一旦计数器增加,它似乎就不会遍历 for 循环一次。或者更明确地说,while 循环只经过一次 for 循环,但它似乎确实在循环,因为它将计数器增加 1 并在 14 处停止。应该注意,输入文件中的行是数字字符串,即为什么我将它们转换为元组,然后检查给定位置的值是大于 column_max 还是小于 column_min。如果是这样,我重新分配 column_max 或 column_min。一旦完成,column_max 和 column_min 将附加到列表(l)中,并且计数器(位置)增加以重复下一列。任何帮助将不胜感激。
input_file = open('names.csv','r')
l= []
column_max = 0
column_min = 0
counter = 0
while counter<14:
for row in input_file:
row = row.strip()
row = row.split(',')
row = tuple(row)
if (float(row[counter]))>column_max:
column_max = float(row[counter])
elif (float(row[counter]))<column_min:
column_min = float(row[counter])
else:
column_min=column_min
column_max = column_max
l.append((column_max,column_min))
counter = counter + 1
【问题讨论】:
-
使用
for i in range(14)而不是while循环。此外,您可能希望使用csvreader而不是由,分割:csvreader将处理包含逗号的字符串。 -
如果有 13 列,您将使用
13作为边界值,而不是14。 -
我会使用
column_max = float('-inf')和column_min = float('inf')而不是column_max = 0和column_min = 0。这样你知道最大值和最小值是正确的。
标签: python