Python:未定义最小值

Python:未定义最小值,python,Python,我使用这段代码来分离最大值和最小值,它在最初几次起作用。但在调试之后,它抛出了未经处理的异常:未定义名称“minimum”。任何一点帮助都将不胜感激,代码不是我自己写的,但我的朋友直到周一才能帮我,我希望在周一之前完成我正在做的事情 import csv # Function to split list l in to n-sized chunks def chunks(l, n): for i in range(0, len(l), n): yield l[i:i

我使用这段代码来分离最大值和最小值,它在最初几次起作用。但在调试之后,它抛出了未经处理的异常:未定义名称“minimum”。任何一点帮助都将不胜感激,代码不是我自己写的,但我的朋友直到周一才能帮我,我希望在周一之前完成我正在做的事情

import csv


# Function to split list l in to n-sized chunks
def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]


# Imports the .csv file
# Note: File must be in same directory as script and named 'data.csv' unless the line below is changed
with open('data.csv') as csvfilein:
    datareader = csv.reader(csvfilein, delimiter=',', quotechar='|')
    data = []
    for row in datareader:
        data.append(row)

data_intervals = chunks(data, 10) # Split array 'data' into intervals of 10 tuples

# CSV writeback to file 'out.csv' in the same folder as script
with open('out.csv', 'wt') as csvfileout:
    # Initialize writer
    datawriter = csv.writer(csvfileout, delimiter=',', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')

    # Write headings to file
    datawriter.writerow(['Interval #', '', 'Min force (kN)', 'Distance (mm)', '', 'Max force (kN)', 'Distance (mm)'])

    interval_count = 1  # Current interval count

    for current_interval in data_intervals: # Iterate through each interval

        # Calculate the min and max values in the current interval based on the SECOND value (force, not distance)
        # This is what the lambda function is for
        try:
            minimum = min(current_interval, key=lambda t: int(t[1]))
            maximum = max(current_interval, key=lambda t: int(t[1]))
        except ValueError:
            pass  # Code was throwing errors for blank entries, this just skips them

        # Write the values for the current interval
        datawriter.writerow([interval_count, '', minimum[1], minimum[0], '', maximum[1], maximum[0]])

        interval_count += 1  # Update count

您可以使用try-except块来处理读取空白条目,然后继续尝试处理它们。此处理代码也应位于
try
块内:

# Calculate the min and max values in the current interval based on the SECOND value (force, not distance)
# This is what the lambda function is for
try:
    minimum = min(current_interval, key=lambda t: int(t[1]))
    maximum = max(current_interval, key=lambda t: int(t[1]))

    # This was originally outside the "try" block
    # Write the values for the current interval
    datawriter.writerow([interval_count, '', minimum[1], minimum[0], '', maximum[1], maximum[0]])

    interval_count += 1  # Update count

except ValueError:
    pass  # Code was throwing errors for blank entries, this just skips them

如果发生异常,则您没有创建变量
最小值
最大值
,因此在尝试访问时会出现错误。
最小值
仅在没有值错误时定义。感谢Martijn,它已修复