并排打印两个函数
这是我第一次使用Python,我在让它输出我想要的格式时遇到了麻烦。我希望输出能够并排显示。可能是因为我累了,我就是搞不明白该怎么做。
我的代码:
def cToF():
c = 0
while c <= 100:
print(c * 9 / 5 + 32)
c += 1
def fToC():
f = 32
while f <= 212:
print((f - 32) / 1.8)
f += 1
print (cToF(),fToC())
输出结果:
all of the numbers from cToF()
all of the numbers from fToC()
我希望的输出结果:
all of the numbers from cToF() all of the numbers from fToC()
2 个回答
0
如果你想要打印出类似这样的内容;
cToF first Element fToC first element
cToF second Element fToC second element
...
你可以把两个列表合并在一起进行打印。
下面是一个你可以使用的示例代码;
import pprint
def cToF():
c = 0
ret_list = []
while c <= 100:
ret_list.append(c * 9 / 5 + 32)
c += 1
return ret_list
def fToC():
f = 32
ret_list = []
while f <= 212:
ret_list.append((f - 32) / 1.8)
f += 1
return ret_list
def join_list(first_list, second_list):
length_of_first_list = len(first_list)
for i, val in enumerate(second_list):
second_list[i] = (" - "if (length_of_first_list-1) < i else first_list[i], val)
return second_list
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(join_list(cToF(), fToC()))
2
目前,cToF函数会运行并打印出所有的值,然后fToC函数也会运行并打印出所有的值。你需要改变生成这些值的方式,这样才能把它们并排打印出来。
# generate f values
def cToF(low=0, high=100):
for c in range(low, high + 1):
yield c * 9 / 5 + 32
# generate c values
def fToC(low=32, high=212):
for f in range(low, high + 1):
yield (f - 32) * 5 / 9
# iterate over pairs of f and c values
# will stop once cToF is exhausted since it generates fewer values than fToC
for f, c in zip(cToF(), fToC()):
print('{}\t\t{}'.format(f, c))
# or keep iterating until the longer fToC generator is exhausted
from itertools import zip_longest
for f, c in zip_longest(cToF(), fToC()):
print('{}\t\t{}'.format(f, c)) # will print None, c once cToF is exhausted
如果你在使用Python 2,请把xrange
替换成range,把izip_longest
替换成zip_longest
。