简体   繁体   English

在python中嵌套for循环不起作用

[英]nested for loop in python not working

We basically have a large xcel file and what im trying to do is create a list that has the maximum and minimum values of each column. 我们基本上有一个大的xcel文件,我想要做的是创建一个列表,其中包含每列的最大值和最小值。 there are 13 columns which is why the while loop should stop once it hits 14. the problem is once the counter is increased it does not seem to iterate through the for loop once. 有13列,这就是为什么while循环应该在它达到14时停止的原因。问题是一旦计数器增加,它似乎不会迭代for循环一次。 Or more explicitly,the while loop only goes through the for loop once yet it does seem to loop in that it increases the counter by 1 and stops at 14. it should be noted that the rows in the input file are strings of numbers which is why I convert them to tuples and than check to see if the value in the given position is greater than the column_max or smaller than the column_min. 或者更明确地说,while循环只通过for循环一次,但它似乎循环,它将计数器增加1并停止在14.应该注意输入文件中的行是数字的字符串,这是为什么我将它们转换为元组,而不是检查给定位置的值是否大于column_max或小于column_min。 if so I reassign either column_max or column_min.Once this is completed the column_max and column_min are appended to a list( l ) andthe counter,(position), is increased to repeat the next column. 如果是这样,我重新分配column_max或column_min。一旦完成,column_max和column_min被附加到列表(l),并且计数器(位置)被增加以重复下一列。 Any help will be appreciated. 任何帮助将不胜感激。

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

I think you want to switch the order of your for and while loops. 我想你要切换forwhile循环的顺序。

Note that there is a slightly better way to do this: 请注意,有一个稍微一点的方式来做到这一点:

with open('yourfile') as infile:
    #read first row.  Set column min and max to values in first row
    data = [float(x) for x in infile.readline().split(',')]
    column_maxs = data[:]
    column_mins = data[:]
    #read subsequent rows getting new min/max
    for line in infile:
        data = [float(x) for x in line.split(',')]
        for i,d in enumerate(data):
            column_maxs[i] = max(d,column_maxs[i])
            column_mins[i] = min(d,column_mins[i])

If you have enough memory to hold the file in memory at once, this becomes even easier: 如果你有足够的内存来同时将文件保存在内存中,这就变得更加容易了:

with open('yourfile') as infile:
    data = [map(float,line.split(',')) for line in infile]
    data_transpose = zip(*data)
    col_mins = [min(x) for x in data_transpose]
    col_maxs = [max(x) for x in data_transpose]

Once you have consumed the file, it has been consumed. 一旦你消耗了文件,它就被消耗了。 Thus iterating over it again won't produce anything. 因此,再次迭代它不会产生任何结果。

>>> for row in input_file:
...     print row
1,2,3,...
4,5,6,...
etc.
>>> for row in input_file:
...     print row
>>> # Nothing gets printed, the file is consumed

That is the reason why your code is not working. 这就是您的代码无法正常工作的原因。

You then have three main approaches: 然后,您有三种主要方法:

  1. Read the file each time (inefficient in I/O operations); 每次读取文件(I / O操作效率低下);
  2. Load it into a list (inefficient for large files, as it stores the whole file in memory); 将其加载到列表中(大文件效率低,因为它将整个文件存储在内存中);
  3. Rework the logic to operate line by line (quite feasible and efficient, though not as brief in code as loading it all into a two-dimensional structure and transposing it and using min and max may be). 重新设计逻辑以逐行操作(非常可行和有效,尽管在代码中不如将其全部加载到二维结构中并转置它并使用minmax可能是这样)。

Here is my technique for the third approach: 这是我的第三种方法的技巧:

maxima = [float('-inf')] * 13
minima = [float('inf')] * 13
with open('names.csv') as input_file:
    for row in input_file:
        for col, value in row.split(','):
            value = float(value)
            maxima[col] = max(maxima[col], value)
            minima[col] = min(minima[col], value)

# This gets the value you called ``l``
combined_max_and_min = zip(maxima, minima)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM