簡體   English   中英

如何在 Python 中聲明用於輸入的全局變量

[英]How to declare a global variable used for input in Python

您好,我是 Python 的新用戶 - 有人可以幫我理解為什么我似乎無法聲明這個全局變量 col_number。 我想嘗試使用 col_number 將其傳遞給繪圖 function。 我嘗試將其聲明為全局變量,但我現在只是在猜測 - 不確定如何解決這個問題。 謝謝

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

    def get_input(prompt):
        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)
                if user_input == 'quit':
                    break
                return user_input
    print(get_input('Enter apples, oranges or q to quit'))
# ######end of input#########################################################################

    for item in my_list:
        print(col_number)

        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

避免全局 state 可能是個好主意。

col_number在這里絕不是全局的。 col_number是 function get_input中的局部變量

要使其成為全局並從 function 訪問它,請在 function 的頂部添加語句global col_number col_number (在使用之前)。

如果將get_input() function 更改為返回col_number ,則不必存儲任何全局 state。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM