簡體   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