Python:最小值未定义

帕多兰

我使用此代码来分离最大值和最小值,并且它在前几次工作。但后来在调试时抛出异常未处理:未定义名称“最小”。任何帮助将不胜感激,代码不是由我自己编写的,但我的朋友直到星期一才能帮助我,我希望在那之前完成我正在做的事情。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章