如何通过python中的函数运行列表? [英] How do I run a list through a function in python?

查看:72
本文介绍了如何通过python中的函数运行列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过我创建的函数运行列表,但始终会出现错误.我不知道怎么了.

I am trying to run my list though a function that I created, but keep getting errors. I don't know what is wrong.

F中的温度:

temp_f =  [19, 21, 21, 21, 23]

功能:

def fahrToCelsius(tempFahrenheit):
    return (tempFahrenheit - 32) /1.8 

该功能有效,例如

fahrToCelsius(temp_f[1])

给予:

-6.111111111111111

-6.111111111111111

但是运行它虽然没有列表.我的尝试:

But running it though a list doesn't. My attempt:

temp_c = []

for i in temp_f:
    temp_c.append (fahrToCelsius(temp_f[i]))

print(temp_c)

给出此错误:

IndexError:列表索引超出范围

IndexError: list index out of range

我尝试了几种不同的方法,但是没有尝试过.你有什么建议吗?谢谢.

I have tried a few different things, but nothing that I have tried works. Do you have any tips? Thanks.

推荐答案

最Python化的解决方案是使用列表理解:

The most pythonic solution is to use list comprehension:

temp_c = [fahrToCelsius(t) for t in temp_f]

这篇关于如何通过python中的函数运行列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆