【问题标题】:How can I write two functions next to each other in python?如何在python中编写两个相邻的函数?
【发布时间】:2019-11-04 08:42:40
【问题描述】:

大家好,我有一个问题,但我无法解决。我提供了输出,但不幸的是我无法获得我想要的输出。

这是我的代码,我希望我的输出看起来像我上传的图片:

    def celiusToFahrenheit():
     print("Celsius\t\t\tFahrenheit")
     for c in reversed(range(31,41)):
        f=(9/5)*c+32
        print(c,"\t\t\t\t",\
              format(f,".1f"))

    def fahrenheitToCelsius():
     print("Fahrenheit\t\t\tCelsius")
     for f in reversed(range(30,130,10)):
        c=(5/9)*(f-32)
        print(f,"\t\t\t\t",\
              format(c,".2f")) 

我得到的输出:

C:\Users\emrea\PycharmProjects\helloworld\venv\Scripts\python.exe C:/Users/emrea/PycharmProjects/helloworld/app.py
Celsius         Fahrenheit
40               104.0
39               102.2
38               100.4
37               98.6
36               96.8
35               95.0
34               93.2
33               91.4
32               89.6
31               87.8
Celsius         Fahrenheit
40               104.0
39               102.2
38               100.4
37               98.6
36               96.8
35               95.0
34               93.2
33               91.4
32               89.6
31               87.8

Process finished with exit code 0

就像我说的,您可以从下面的链接中找到我想要的输出。 https://i.stack.imgur.com/swcx6.png

The Output

【问题讨论】:

  • 发布完整的错误和回溯

标签: python python-3.x python-2.7 optimization python-requests


【解决方案1】:

如果要对齐值,可以指定长度和对齐方式。 见https://docs.python.org/3/library/string.html#format-specification-mini-language

添加到上面@L3viathan 的答案...

def celiusToFahrenheit():
    yield "{:^12} {:^12}".format("Celsius", "Fahrenheit")
    yield "-"*25
    for c in reversed(range(31, 41)):
        f = (9 / 5) * c + 32
        yield "{:12} {:>12}".format(c, format(f, ".1f"))


def fahrenheitToCelsius():
    yield "{:^12} {:^12}".format("Fahrenheit", "Celsius")
    yield "-"*25
    for f in reversed(range(30, 130, 10)):
        c = (5 / 9) * (f - 32)
        yield "{:12} {:>12}".format(f, format(c, ".1f"))


for left, right in zip(celiusToFahrenheit(), fahrenheitToCelsius()):
    print(left, "|", right)

【讨论】:

    【解决方案2】:

    生成器非常适合:yield 他们的行:而不是在函数内部打印:

    def celiusToFahrenheit():
        yield "Celsius\t\t\tFahrenheit"
        for c in reversed(range(31, 41)):
            f = (9 / 5) * c + 32
            yield "{}\t\t\t\t{}".format(c, format(f, ".1f"))
    
    def fahrenheitToCelsius():
        yield "Fahrenheit\t\t\tCelsius"
        for f in reversed(range(30, 130, 10)):
            c = (5 / 9) * (f - 32)
            yield "{}\t\t\t\t{}".format(f, format(c, ".1f"))
    

    然后你可以同时遍历两者:

    for left, right in zip(celiusToFahrenheit(), fahrenheitToCelsius()):
        print(left, "|", right)
    

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多