gpt4 book ai didi

Python - 从满足条件的嵌套列表中获取索引

转载 作者:行者123 更新时间:2023-11-28 21:05:04 25 4
gpt4 key购买 nike

有人可以帮助我在使用 Python 2.7 满足特定条件的嵌套列表中获取项目的索引吗?我知道 StackOverflow 上也有类似的问题,但我似乎找不到处理“嵌套”列表的好例子。

我有一个长达数十万行的数据列表,格式如下:

data =[
["","","","28.04.2015 09:34:38",1.52411,1.52428,17],
["","","","28.04.2015 09:34:40",1.52415,1.52433,18],
["","","","28.04.2015 09:34:42",1.52425,1.52444,19],
["","","","28.04.2015 09:34:44",1.52417,1.52435,18],
["","","","28.04.2015 09:34:46",1.52421,1.52440,19],
["","","","28.04.2015 09:34:48",1.52426,1.52446,20],
["","","","28.04.2015 09:34:50",1.52429,1.52444,15],
["","","","28.04.2015 09:34:58",1.52423,1.52441,18],
["","","","28.04.2015 09:35:00",1.52416,1.52434,18],
["","","","28.04.2015 09:35:02",1.52416,1.52433,17],
["","","","28.04.2015 09:35:04",1.52416,1.52434,18],
["","","","28.04.2015 09:35:06",1.52406,1.52422,16],
["","","","28.04.2015 09:35:10",1.52406,1.52421,15],
["","","","28.04.2015 09:35:14",1.52427,1.52444,17],
["","","","28.04.2015 09:35:16",1.52424,1.52443,19],
["","","","28.04.2015 09:35:18",1.52434,1.52453,19],
["","","","28.04.2015 09:35:20",1.52434,1.52451,17],
["","","","28.04.2015 09:35:22",1.52438,1.52456,18],
["","","","28.04.2015 09:35:24",1.52432,1.52451,19],
["","","","28.04.2015 09:35:28",1.52445,1.52464,19],
["","","","28.04.2015 09:35:34",1.52435,1.52451,16],
["","","","28.04.2015 09:35:36",1.52432,1.52449,17],
["","","","28.04.2015 09:35:38",1.52429,1.52448,19]]

对于每一行,我想将“第 5 列”(十进制数字的第一列)中的数据与某个值(以 1.52440 为例)进行比较,并返回数据更大的第一行的索引比我确定的值。

我已经编写了使用 for-row-in-data 类型循环以“传统”方式执行此操作的代码,但我想尽可能使用更好(更快)的方法,但似乎无法产生预期的结果。

到目前为止我所做的相当糟糕的尝试是:

pricedata = [n[4] for n in data]
myindex = (x for x in enumerate(pricedata) if x > 1.5440).next()

第一行提取价格数据 col 作为新列表。我不确定这是否真的有必要,但由于我对列表理解的理解很差,所以我试图将事情分解成我能理解的步骤。

我不太明白第二行在做什么,但它似乎返回 (0, 1.52411) - 列表中的第一项 - 无论我输入什么比较值。

我也试过:

myindex = [x for x in enumerate(pricedata) if x > 1.5440][0]

而且它似乎产生了相同的结果。

我以为理解是在说:

“如果您正在查看的价格大于 1.5440,请为您在索引价格列表中查看的每个价格制作一个价格列表”,但看来我错了!

请有人指出我方法的错误并帮助我吗?感谢您的帮助!

最佳答案

问题是,您正在比较元组和 float ,因为 enumerate返回索引和项目的元组,然而,在 Python 2 中,元组被视为大于 float :

>>> () > 4.
True

因此,enumerate 产生的第一个元组总是产生匹配。


要解决这个问题,您应该先解压元组,然后使用next 返回生成器表达式中的第一个匹配索引:

next(i for i, x in enumerate(data) if x[4] > 1.52415)

关于Python - 从满足条件的嵌套列表中获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com