如何在Python中声明用于输入的全局变量 [英] How to declare a global variable used for input in Python
问题描述
你好,我是Python的新用户-有人可以帮助我理解为什么我似乎无法声明此全局变量col_number.我想尝试使用col_number将其传递给绘图函数.香港专业教育学院试图将其声明为全局变量,但我现在只是猜测-不确定如何解决此问题.谢谢
Hello I am new user to Python - Could somebody help me understand why i cant seem to declare this global variable col_number. I want to try and use the col_number to pass it to the plotting function. Ive tried declaring it as a global variable but I am just guessing now - not really sure how to fix this. Thanks
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()
输入文件
名称1,名称2,名称3,名称4,名称5,名称6,名称7,名称81,10,19,4,蓝色,6,7,82,11,20,4,蓝色,6,7,83,12,21,4,蓝色,6,7,84,13,22,4,绿色,6,7,85,14,23,4,绿色,6,7,86,15,24,4,蓝色,6,7,87,16,25,4,蓝色,6,7,88,17,26,4,黄色,6,7,89,18,27,4,黄色,6,7,8
input file
Name1,Name2,Name3,Name4,Name5,Name6,Name7,Name8 1,10,19,4,Blue,6,7,8 2,11,20,4,Blue,6,7,8 3,12,21,4,Blue,6,7,8 4,13,22,4,Green,6,7,8 5,14,23,4,Green,6,7,8 6,15,24,4,Blue,6,7,8 7,16,25,4,Blue,6,7,8 8,17,26,4,Yellow,6,7,8 9,18,27,4,Yellow,6,7,8
推荐答案
避免全局状态可能是个好主意.
col_number
在这里绝不是全局的. col_number
是函数 get_input
col_number
is in no way global here. col_number
is local variable in your function get_input
要使其成为全局代码并从您的函数访问它,请在函数顶部(使用之前)添加语句 global col_number
.
To make it global and access it from your function add the statement global col_number
at the top of your function (before you use it).
如果将您的 get_input()
函数更改为返回 col_number
,则不必存储任何全局状态.
If you change your get_input()
function to return col_number
you don't have to store any global state.
这篇关于如何在Python中声明用于输入的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!