首页 > 解决方案 > 如何为列表中的每个元素添加转换因子?

问题描述

我正在尝试将转换因子(F 到 C)添加到从用户输入生成的列表中,以作为单独的列表输出。我该怎么做呢?

我会为我目前拥有的东西写一些代码

userEntry = int(input("Please enter a fahrenheit:"))

listofFahrs =[userEntry]

for i in range(4):
    i +=1
    listofFahrs.append(int(input("Please enter another fahrenheit:")))
    # convert to string if need be for output
    userList = str(listofFahrs[0:6])


fahrToCels =(userEntry - 32) * 5 / 9
celsConversion = [x + fahrToCels for x in listofFahrs]

当我尝试 print(celsConversion) 时,我遇到了一些奇怪的行为......例如,为所有 5 个整数输入 1 产生 -16.2 ,这比转换应该是高1度(即它应该输出 - 17.2

当我尝试输入诸如 1,2,3,4,5 之类的列表时……它似乎添加了一个并将列表返回给我……

在这一点上,我已经通过向 fahrtoCels 添加 -1 来补偿,但我想知道是否有任何更清洁的方法可以做到这一点。

如果您能提供帮助,请提前致谢!

标签: pythonpython-3.xlistmath

解决方案


创建一个接收华氏值并返回摄氏值的listofFahrs函数,使用列表推导将您中的每个元素传递给该函数。

def fahrToCels(fahr):
    return round((fahr - 32) * 5 / 9,2)

listofFahrs =[]
for i in range(5):
    listofFahrs.append(int(input("Please enter a fahrenheit value:")))

celsConversion = [fahrToCels(x)  for x in listofFahrs]

推荐阅读