将程序转换为Python中的函数?
在Python类的家庭作业中,我们必须创建一个函数,该函数接受字符串S,并创建一个嵌套的字符串数列表(元素必须是浮点数),以分号分隔。例如,字符串: “3.519.242;27015;318-2” 应提供以下清单: [3.5,1.0,9.2,4.0],[2.0,7.0,0.0,15.0],[3.0,1.0,8.0,-2.0]] 我终于能够编写程序了:将程序转换为Python中的函数?,python,function,variables,Python,Function,Variables,在Python类的家庭作业中,我们必须创建一个函数,该函数接受字符串S,并创建一个嵌套的字符串数列表(元素必须是浮点数),以分号分隔。例如,字符串: “3.519.242;27015;318-2” 应提供以下清单: [3.5,1.0,9.2,4.0],[2.0,7.0,0.0,15.0],[3.0,1.0,8.0,-2.0]] 我终于能够编写程序了: S = "3.5 1 9.2 4;2 7 0 15;3 1 8 -2" i = 0 z = 0 temp_list = [] good_list
S = "3.5 1 9.2 4;2 7 0 15;3 1 8 -2"
i = 0
z = 0
temp_list = []
good_list = []
str_temp = ""
S_temp = S.split(";")
while i < len(S_temp):
str_temp = S_temp[i]
temp_list = str_temp.split(" ")
while z < len(temp_list):
temp_list[z] = float(temp_list[z])
z += 1
z = 0
good_list.append(temp_list)
i += 1
S=“3.519.242;27015;318-2”
i=0
z=0
临时列表=[]
好的清单=[]
str_temp=“”
S_temp=S.split(“;”)
当我
然而,我现在被困在试图找出如何转换成一个函数
我想应该是这样的:
def testfunction(S):
S_temp = S.split(";")
while i < len(S_temp):
str_temp = S_temp[i]
temp_list = str_temp.split(" ")
while z < len(temp_list):
temp_list[z] = float(temp_list[z])
z += 1
z = 0
good_list.append(temp_list)
i += 1
def测试函数:
S_temp=S.split(“;”)
当我
但是,当我保存它并尝试运行testfunction(在将S指定为与原始程序相同的字符串后)时,我得到以下错误:
UnboundLocalError:赋值前引用的局部变量“i”
这是怎么回事?我不是要得到一个直接的答案,而是一个或两个提示,这样我就可以弄明白并从中吸取教训
谢谢。在使用变量之前,您不会初始化变量。i,good_list和z的情况也一样
def testfunction(S):
S_temp = S.split(";")
i=0
good_list=[]
while i < len(S_temp):
str_temp = S_temp[i]
temp_list = str_temp.split(" ")
z=0
while z < len(temp_list):
temp_list[z] = float(temp_list[z])
z += 1
z = 0
good_list.append(temp_list)
i += 1
def测试函数:
S_temp=S.split(“;”)
i=0
好的清单=[]
当我
在您的代码中,因为您没有为i
指定初始值,所以出现了该错误!
请注意,在引用之前,始终需要分配变量
作为一种更具python风格的方式,您可以使用:
因此,对于创建函数,您可以将s
作为其参数传递:
def seperator(s):
return [map(float,i) for i in [n.split() for n in s.split(';')]]
出现该错误的原因是您忘记在函数体中包含
i=0
;您还应该包括z=0
和初始化good\u列表
。在分配S_temp
任务后声明这两项
您还应该对变量使用小写,在Python中,您不需要知道序列的长度就可以对其进行迭代。因此,i
确实不是必需的,z
也不是必需的。最后,您需要返回结果
最后,您的代码应该是这样的:
def test_function(s):
good_list = []
for i in s.split(';'):
temp_list = [] # empty list
for z in i.split(" "):
temp_list.append(float(z))
good_list.append(temp_list)
return good_list # you forgot to return the result
函数中的
i=0
在哪里?您没有将变量初始化放入函数中。应该是comment@vks我只是想让他看看密码。我想只要我一提,他就无法理解我。
def test_function(s):
good_list = []
for i in s.split(';'):
temp_list = [] # empty list
for z in i.split(" "):
temp_list.append(float(z))
good_list.append(temp_list)
return good_list # you forgot to return the result