这里是 Python 新手,运行 2.7。
我正在尝试创建一个程序,该程序使用函数生成文本,然后将函数生成的文本输出到文件。
当仅在 powershell 中打印函数时(如:http://codepad.org/KftHaO6x),它会按照我的意愿进行迭代:
def writecode (q, a, b, c):
while b < q:
b = b + 1
print "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,b,c,a,a,a,b,c)
print "votes%d_%d.append(v%d_%d_%d)" % (b,c,a,b,c,)
print "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,c,b,a,a,a,c,b)
print "votes%d_%d.append(v%d_%d_%d)" % (c,b,a,c,b)
writecode (5,1,0,4)
当试图将函数输出到文件中时(像这样:http://codepad.org/8GJpp9QY),它只给出 1 个值,即不迭代:
def writecode (q, a, b, c):
while b < q:
b = b + 1
data_to_write = "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,b,c,a,a,a,b,c)
data_to_write_two = "votes%d_%d.append(v%d_%d_%d)" % (b,c,a,b,c,)
data_to_write_three = "v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" %(a,c,b,a,a,a,c,b)
data_to_write_four = "votes%d_%d.append(v%d_%d_%d)" % (c,b,a,c,b)
return data_to_write
return data_to_write_two
return data_to_write_three
return data_to_write_four
x = writecode (5,1,0,4)
out_file = open("code.txt", "a")
out_file.write(x)
out_file.close()
这是为什么,我怎样才能使输出函数迭代(就像打印一样)?
最佳答案
你的问题是你只能从一个函数返回
一次:
def test():
return 1
return 2
x = test()
# x is now 1
您需要使用 yield
或返回值的元组:
def this_will_work():
yield 1
yield 2
x = list(this_will_work()) # See below for why we are using list
# x is now [1, 2]
def so_will_this:
return 1, 2
x = so_will_this()
# x is now (1, 2)
使用 yield
将您的函数转换为 generator
可以迭代 - 如果您只对所有最终值感兴趣,您可以使用 list
将生成器转换为生成器产生的所有值的列表。或者,您可以使用 for ... in
循环它。
关于python - 函数迭代打印但不返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11766900/