所以我是编码的新手,这是我的第一个问题,所以如果格式不正确,我道歉。
我试图弄清楚如何组合(get_x_start)和(get_x_end)函数{其中x是赋予函数对的唯一名称},这样每个x返回一个函数(字段)和(结束)。我尝试使用一个列表,即:
return (field,end)
但是当我尝试时,我不知道如何在(main())中使用那些作为单独的参数,这样函数(fetch_data)可以使用来自单个x函数的两个返回参数。
我的代码如下。如果其中的任何内容不清楚,请告诉我,我会尽力澄清。感谢。
def get_data (url):
response = url
return str(response.read())
def fetch_data (field,data,end):
sen = data[data.find(field)+len(field)+3:data.find(end)-3]
return sen
def get_name_start (data):
field = "Name"
return field
def get_name_end (data):
end = "ClosingTime"
return end
def get_open_start (data):
field = "OpeningTime"
return field
def get_open_end (data):
end = "Name"
return end
def get_close_start (data):
field = "ClosingTime"
return field
def get_close_end (data):
end = "CoLocated"
return end
def main ():
import urllib.request
data = get_data (urllib.request.urlopen('http://www.findfreewifi.co.za/publicjson/locationsnear?lat=-33.9568396&lng=18.45887&topX=1'))
print (fetch_data(get_name_start(data),data,get_name_end(data)))
print (fetch_data(get_open_start(data),data,get_open_end(data)))
print (fetch_data(get_close_start(data),data,get_close_end(data)))
main ()
答案 0 :(得分:2)
Here it is a function that returns a tuple
def return_ab():
return 5, 6
Here it is a function that accepts three arguments
def test(a, b, c):
print(a, b, c)
And here it is how you can call the test()
function passing it the two parameters returned by return_ab()
but unpacked
test(*return_ab(), 7) # => 5 6 7
The key point is the asterisk in front of return_ab()
. It's a relatively new syntax that is very useful indeed...
答案 1 :(得分:0)
From this post here multiple variables can be returned like this
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
From here you can then pass your variables into the new function like:
new_f(succeeded, b)
Hope this helps