这里是代码!python:正确使用全局变量
import csv
def do_work():
global data
global b
get_file()
samples_subset1()
return
def get_file():
start_file='thefile.csv'
with open(start_file, 'rb') as f:
data = list(csv.reader(f))
import collections
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
return
def samples_subset1():
with open('/pythonwork/samples_subset1.csv', 'wb') as outfile:
writer = csv.writer(outfile)
sample_cutoff=5000
b_counter=0
global b
b=[]
for row in data:
if counter[row[10]] >= sample_cutoff:
global b
b.append(row)
writer.writerow(row)
#print b[b_counter]
b_counter+=1
return
我是python的初学者。我的代码运行的方式是我调用do_work,do_Work将调用其他函数。这里是我的问题:
如果我需要
data
仅通过2的功能可以看出,我应该让全球?如果不是那么我应该怎么称呼samples_subset1
?我应该从get_file
还是从do_work
拨打电话?该代码的作品,但你能指出其他写好的/坏的事情吗?
我正在处理一个csv文件,并且有多个步骤。我将步骤划分为不同的功能,如
get_file
,samples_subset1
,还有更多的我会添加。我是否应该继续按照我现在所做的方式进行操作?在这里,我打电话给每个单独的功能do_work
?
这里是新的代码,根据下面的答案之一:
import csv
import collections
def do_work():
global b
(data,counter)=get_file('thefile.csv')
samples_subset1(data, counter,'/pythonwork/samples_subset1.csv')
return
def get_file(start_file):
with open(start_file, 'rb') as f:
global data
data = list(csv.reader(f))
counter = collections.defaultdict(int)
for row in data:
counter[row[10]] += 1
return (data,counter)
def samples_subset1(data,counter,output_file):
with open(output_file, 'wb') as outfile:
writer = csv.writer(outfile)
sample_cutoff=5000
b_counter=0
global b
b=[]
for row in data:
if counter[row[10]] >= sample_cutoff:
global b
b.append(row)
writer.writerow(row)
#print b[b_counter]
b_counter+=1
return
非常感谢你 – 2010-07-28 15:08:41
为了不听起来像“做这样做!” - 想象你想要导入几个文件。或者将几个数据集应用于处理函数。然后,你想能够告诉函数它应该工作的是什么 - 这将会随着全局变量方法变得丑陋。我不认为我曾经在我的代码中找到需要全局变量的东西,这不是基于我个人的懒惰;) – Nicolas78 2010-07-28 15:09:56
哦,并使start_file为get_file的参数,而你在它:) – Nicolas78 2010-07-28 15:10:57