繁体   English   中英

在模块级别未定义的全局变量

[英]Global variable undefined at the module level

我有这个程序,它在一个简单的 csv 文件中读取,过滤该文件中的一列以获取颜色。 然后分别为每种不同的颜色写出 csv 文件。 然后绘制一个图表,比较每个过滤后的 output 文件的列。 但它仍然运行有一些错误

我之前发布了这个问题,但仍然有问题。 如果有人可以帮助我的错误代码! 我的问题是

当我不得不定义它两次时,我不明白为什么我得到“命名 col_number 变量未定义”(第 58 行)。 我知道这是不好的代码,但如果有人可以帮助我。

另外,我试图在程序运行时传递 user_input(在这种情况下,苹果、梨或橙子成为 y 轴标题。我尝试在 return 语句中包含在 col_number 之后并更改 plt.title 中的数据标签('Data v Time') 到 plt.title(user_input + 'v Time') 但消息未解析引用。

感谢您的帮助,我的代码如下

from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import csv
# import random used for changing line colors in chart
import random
from itertools import cycle

# opens a the input file and reads in the data
with open('Test_colours_in.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
# prints list of unique values in column 5 of csv of input file
    my_list = set()
    for line in csv_reader:
        my_list.add(line['Name5'])
    print(my_list)

# takes these unique values and creates files associated with each unique value
    for item in my_list:
        with open(item + '_'+'Test.csv', 'w', newline='') as new_file:
            fieldnames = ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6', 'Name7', 'Name8']
            csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
            csv_writer.writeheader()

# filters the original file for each item in the list of unique values and writes them to respective file
            csv_file.seek(0)  # Reposition to front of file
            filtered = filter(lambda r: r['Name5'] == item, csv_reader)
            for row in filtered:
                csv_writer.writerow(row)

# Section of code below plots data from each of the filtered files

#
    my_color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray', 'b', 'g', 'r',
                     'c', 'm', 'y', 'tab:blue', 'tab:orange', 'tab:purple', 'tab:gray']

# ###################################################################
# ## trying to get this to do the same as the current input commands
    #global col_number
    def get_input(prompt):
        global col_number
        while True:
            user_input = input(prompt).lower()
            if user_input in ('apples', 'pears', 'oranges', 'quit'):
    # the user = int(0),int(1), int(2) values just assign a different column numnber
                if user_input == 'apples':
                    col_number = int(0)
                if user_input == 'pears':
                    col_number = int(1)
                if user_input == 'oranges':
                    col_number = int(2)
                return col_number,
print(get_input('Enter apples, pears, oranges or q to quit'))
# ######end of input#########################################################################col_number = get_input(prompt)

for item in my_list:

    x, y = np.loadtxt(item + '_'+'Test.csv', skiprows=1, usecols=[0, col_number], unpack=True, delimiter=',')
    color = random.choice(my_color_list)
    plt.plot(x, y, color, label=item, linewidth=5)

    style.use('ggplot')

plt.title('Data v Time')
plt.ylabel('Data')
plt.xlabel('Time seconds')

plt.legend()
plt.grid(True, color='k')
plt.show()

下面的数据文件

Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8 1,10,19,4,蓝色,6,7,8 2,11,20,4,蓝色,6,7,8 3,12,21 ,4,蓝色,6,7,8 4,13,22,4,绿色,6,7,8 5,14,23,4,绿色,6,7,8 6,15,24,4,蓝色, 6,7,8 7,16,25,4,蓝色,6,7,8 8,17,26,4,黄色,6,7,8 9,18,27,4,黄色,6,7,8

为了解决您的具体问题, col_number不需要是全局的。 看看你在做什么:

def get_input(prompt):
    global col_number
                col_number = ...
            return col_number,

您根本不使用col_number的(未设置)值,您只需设置它。 设置后,您返回相同的值!

所以忘记有一个全局变量。 只需将col_number分配给 function 的结果:

def get_input(...):
    result = ...
    return result

# elsewhere in your code:
col_number = get_input(...)
... use col_number ...

暂无
暂无

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

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