Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将MyFunction应用于列表列表_Python_List - Fatal编程技术网

Python将MyFunction应用于列表列表

Python将MyFunction应用于列表列表,python,list,Python,List,我编写了一个函数,根据从列表中获取的两个值执行计算,然后附加结果。我想知道如何调整此函数以对列表列表中的所有列表执行计算,到目前为止,我遇到了令人沮丧的失败 到目前为止,我知道这是可行的: import datetime Horse = ['Sea Biscuit', '10:57:06', '10:58:42'] #My Function used to get times from the list and calculate speed in MPH def get_speed():

我编写了一个函数,根据从列表中获取的两个值执行计算,然后附加结果。我想知道如何调整此函数以对列表列表中的所有列表执行计算,到目前为止,我遇到了令人沮丧的失败

到目前为止,我知道这是可行的:

import datetime

Horse = ['Sea Biscuit', '10:57:06', '10:58:42']

#My Function used to get times from the list and calculate speed in MPH

def get_speed():
    time1 = Horse[1]
    time2 = Horse[2]
    d = 1    #Assuming a distance of 1 mile
    FMT = '%H:%M:%S'
    tdelta = datetime.datetime.strptime(time2, FMT) - datetime.datetime.strptime(time1, FMT)
#Convert from timedelta HH:MM:SS format to hours by first converting to a string
    stringtime=str(tdelta)
    parts = stringtime.split(':')
    hours = int(parts[0])*1 + int(parts[1])/60 + int(parts[2])/3600

    speed = round((d/hours),2)

    Horse.append (speed)

get_speed()   
因此,我要调整此函数的列表如下所示:

Horses = [['Sea Biscuit', '10:57:06', '10:58:42']['Red Rum', '10:57:06', '10:59:02']['Blazing saddles', '10:57:06', '10:59:16']]

非常感谢您的建议和帮助

可能存在更优雅的基于类的解决方案,但处理问题的最快方法是使用for循环:

for horse in Horses:
  def get_speed(horse)

然后,您就不想知道输出存储在哪里。

这取决于您想如何输出数据。尽管我将通过考虑您希望输出也是一个列表来回答这个问题

Python的
Map
函数可能是您想要了解的内容:

你可以这样做:

times = map(get_speed, Horses)
基本上是,(语法)

Map在列表的每个成员上运行该函数

这里有一个关于python中Map函数的有趣讨论:答案还解释了Map实际上是如何感觉像一个嵌套的循环函数调用的

编辑: 顺便说一句,这里有一个运行代码。注意我所做的更改。子列表需要一个逗号,除法需要用十进制数,而不是整数来完成,否则在下一步尝试进行速度除法时,您可能会得到一个零除法(不过,您也可以在那里检查零!)

链接:

编辑2: OP使用的是Python 3。在Python3中,映射不返回列表,而是向列表返回迭代器。因此,代码需要更改以添加以下内容:

return Horse    #Returns the changed horse object back to map

Horses = list(map(get_speed, Horses))    #convert iterator back to list
在此处运行代码:


虽然可以避免映射到列表的转换,并直接作为一个普通的迭代器来迭代列表(也可以更高效!)

Wow!感谢您迅速而全面的回复。我会按照链接做我的家庭作业!打印(马)仅显示原始列表,而不附加速度-返回到绘图板:-/ideone示例显示了这一点。你看到输出了吗?嗯,是的,我看到了。。。我可以看到你的输出打印,但我的只是打印原始列表,没有附加速度。这就好像times=map(获得速度,马)实际上什么都没有做。时间是问题所在-是吗?你实际上不需要把结果放入时间!(你知道我没有打印它。)事实上。。。非常感谢!它正在将输出添加到每个列表中,这正在打败我!!
return Horse    #Returns the changed horse object back to map

Horses = list(map(get_speed, Horses))    #convert iterator back to list