2014-10-18 32 views
1

这是我第一次使用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()) 

OUTPUT:

all of the numbers from cToF() 
all of the numbers from fToC() 

我怎么想的输出:

all of the numbers from cToF() all of the numbers from fToC() 
+1

为了使您的输出更有用,我建议您的每个函数都应该打印_two_数字,它转换的温度以及转换的温度。但即使你不这样做,如果你想输出并排,你需要特别小心,因为'cToF()'打印100行,而'fToC()'打印180行。 – 2014-10-18 05:15:29

回答

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的范围和izip_longestzip_longest

+0

这似乎打印正确,但'fToC()'停止打印时,它击中了'55.55555555555556' – 2014-10-18 05:12:56

+0

这是因为'zip'截断到最短迭代。 'cToF'生成100个值,而'fToC'则生成180个值。你可以使用['itertools.zip_longest'](https://docs.python.org/3/library/itertools.html#itertools.zip_longest)而不是'zip'来获得最长的结果。 – davidism 2014-10-18 05:15:22

+0

哦好吧,酷蟒是真棒有这么多有用的功能,你可以使用:D – 2014-10-18 05:22:03

0

如果你想打印像;

cToF first Element fToC first element 
cToF second Element fToC second element 
... 

你可以加入2个列表来列印它。

您可以使用的示例代码;

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()))