python - 如何为列表中的每个元素添加转换因子?
问题描述
我正在尝试将转换因子(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 来补偿,但我想知道是否有任何更清洁的方法可以做到这一点。
如果您能提供帮助,请提前致谢!
解决方案
创建一个接收华氏值并返回摄氏值的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]
推荐阅读
- python - Python TCP服务器:通过与侦听端口不同的端口为客户端提供服务
- python - 如何提高我在迁移学习 Resnet50 中的验证准确性?
- python - 在脚本中保存对象
- wordpress - 如何在 WordPress 中阻止自定义帖子类型列表页面?
- android - 当我们在浏览器中搜索链接时,我们如何重定向到我们的 react-native 应用程序
- javascript - javascript setTimeout 函数,有问题吗
- android - 使用一个启动器分屏启动我的两个应用程序 - Android
- c# - 如何增加 ASP .NET Core 3.0 应用程序中的最大线程数
- python - python使用urllib2和urllib获取请求问题
- c++ - 我创建了一个库,想知道设计是否效率低下