【问题标题】:passing a list as input传递一个列表作为输入
【发布时间】:2023-03-30 16:49:01
【问题描述】:

我有这个简单的摄氏到华氏代码。我无法创建要输出的 10 天列表。我可以输入一个输入,它给我华氏温度,但我不知道如何输入 10 天的列表以输出计算以及它是凉爽还是温暖。

tmp = int(input("Input the  temperature you like to convert from Celsius to Fahrenheit? (e.g.,10) : "))
lst = [tmp]
i = 0
for i in range(len(lst)):
    lst[i] = (lst[i] * 1.8) + 32
    print(lst, "This is the fahrenheit temps")

if tmp < 0:
    print('Freezing weather.\n')
elif tmp < 10:
    print('Very cold weather.\n')
elif tmp < 20:
    print('Cool weather\n')
elif tmp < 30:
    print('Normal temps.\n')
elif tmp < 40:
    print("It's hot outside.\n")
else:
    print("You should properly stay inside")

【问题讨论】:

  • 您是否会说您面临的问题更多地与传递列表作为输入有关,而与您期望温度数据的事实关系不大?如果是这样,我建议您编辑问题的标题以反映这一点
  • @PaulH 谢谢。我就是这么做的。
  • 我给你个提示:"23,25,12,56".split()
  • 提示 2:str.split() 返回 字符串 列表。你需要它们是数字。

标签: python for-loop input


【解决方案1】:

好的,所以我根据您的需要重新编写了您的代码

temps = map(float, input("Input the temperature you'd like to convert from Celsius to Fahrenheit: ").split(',')) #split it with comma (,) and then convert every item into float
for temp in temps: #loop through the values
    fahrenite = temp * 9/5 + 32 #calculate
#blah blah
    if temp< 0:
        extra = "Freezing weather."
    elif temp< 10:
        extra = "Very cold weather."
    elif temp< 20:
        extra = "Cool weather"
    elif temp< 30:
        extra = "Normal temps."
    elif temp< 40:
        extra = "It's hot outside."
    else:
        extra = "You should properly stay inside"
#print everything
    print(f"{temp}℃  in Fahrenheit is {fahrenite}℉  that is {extra}")

还有一件事......使用逗号 (,) 分隔您的输入

【讨论】:

    【解决方案2】:

    一种方法是将不同的临时变量分成不同的输入变量,并将它们以实物形式附加到列表中,然后使用您的函数遍历列表。

    像这样:

    inputting = True
    temps = []
    while inputting:
        temp = int(input("Temp"))
        temps.append(temp)
        cond = input("continue? y/n")
        if cond in "Nn":
            inputting = False
    
    def c_to_f(temperature):
        return temperature * 1.8 + 32
    
    for temp in temps:
        print(c_to_f(temp))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      相关资源
      最近更新 更多