gpt4 book ai didi

python - 将文件和值作为参数传递给 python 中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:23 26 4
gpt4 key购买 nike

我是一个python新手。我正在尝试运行这个简单的 python 示例。我希望将文件和某些值作为参数传递给我的函数 latcalc()。谁能建议我如何将我的文件和值作为参数传递。或者是否有更好的方式/方法来做这些事情。

#!/usr/bin/python

# include the constants

min_length = 1
max_length = 30


# delays

delay = 100

# Speed of light

c_vaccum = 3e8

global filename1
global filename2
global filename3

def openfiles():

filename1 = open("file1.txt", "w")
filename2 = open("file2.txt", "w")
filename3 = open("file3.txt", "w")

def latcalc(filename,target_name,vf):


target_name = 0

for length in range(min_length, max_length):
if length < 2:
target_name += (length/(vf * c_vaccum))
elif length == 2:
target_name += delay
else:
target_name = target_name

myline="%s\t%s\n" % (length, target_name)
filename.write(myline)


openfiles()
latcalc(filename1,lat40,0.4)
latcalc(filename2,lat80,0.8)
latcalc(filename3,lat100,1)

最佳答案

我会创建一个小类(给它一个有用的名称)来封装您的数据。如果您的文件增长,您只需更改您的 create_lats

min_length = 1
max_length = 30

# delays
delay = 100

# Speed of light
c_vaccum = 3e8

#Little class to keep our data in one place
class Lat:
def __init__(self, filename, factor):
self.filename = filename
self.factor = factor
self.file = open(filename, "w") #let the class open the file


#now our function needs only one parameter, neat!
def latcalc(lat):
target_name = 0

for length in range(min_length, max_length):
if length < 2:
target_name += (length / (lat.factor * c_vaccum)) #acces the class variable
elif length == 2:
target_name += delay
else:
target_name = target_name

myline = "%s\t%s\n" % (length, target_name)
lat.file.write(myline)


def create_lats():
lats = []
lats.append(Lat("file1.txt", 0.4))
lats.append(Lat("file2.txt", 0.8))
lats.append(Lat("file3.txt", 1))
return lats


#loop over your lats created in create_lats
for lat in create_lats():
latcalc(lat)
lat.file.close() #close the file

关于python - 将文件和值作为参数传递给 python 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33918654/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com