如何获得列表索引?

时间:2016-06-17 05:28:07

标签: python

>>> ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75), 
            (735982.0, 76.5, 77.0, 75.0, 75.25),
            (735983.0, 75.75, 75.75, 74.25, 75.0),
            (735984.0, 75.0, 76.25, 74.5, 75.5)]
>>> print (ohlc.index("735982.0"))
>>> ValueError: '735982.0' is not in list

从代码我想得到索引结果= 1,但我不能这样做。

谢谢。

3 个答案:

答案 0 :(得分:1)

你想要像

这样的东西
[idx for idx,o in enumerate(ohlc) if o[0]==735982.0][0]

> 1

P.S。确保在列表中不存在元素的情况下添加try / catch

答案 1 :(得分:1)

您的ohlc列表是元组列表。所以你必须给元组找到像这样的索引值。

In [1]: ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75), 
   .....:             (735982.0, 76.5, 77.0, 75.0, 75.25),
   .....:             (735983.0, 75.75, 75.75, 74.25, 75.0),
   .....:             (735984.0, 75.0, 76.25, 74.5, 75.5)]
In [2]: ohlc.index((735982.0, 76.5, 77.0, 75.0, 75.25))
Out[1]: 1

索引是列表中元素的位置。您也可以使用索引找到元素。像ohlc[1]一样。它返回相应的元素。

如果要查找具有735982.0浮点值的索引值,可以这样实现。

In [3]: [i[0] for i in ohlc].index(735982.0)
Out[2]: 1

但总是更好地使用enumerate来查找索引值。

In [4]: for index,value in enumerate(ohlc):
   .....:     print index,"...",value
   .....:     
0 ... (735981.0, 74.25, 77.25, 73.75, 75.75)
1 ... (735982.0, 76.5, 77.0, 75.0, 75.25)
2 ... (735983.0, 75.75, 75.75, 74.25, 75.0)
3 ... (735984.0, 75.0, 76.25, 74.5, 75.5)

答案 2 :(得分:1)

ohlc是一个元组列表,所以,

你可以这样做,只匹配元组的第一个元素:

ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),(735982.0, 76.5, 77.0, 75.0, 75.25),(735983.0, 75.75, 75.75, 74.25, 75.0),(735984.0, 75.0, 76.25, 74.5, 75.5)]
a=[ohlc.index(item) for item in ohlc if item[0] == 735981]
print(a)

全部搜索:

ohlc = [(735981.0, 74.25, 77.25, 73.75, 75.75),(735982.0, 76.5, 77.0, 75.0, 75.25),(735983.0, 75.75, 75.75, 74.25, 75.0),(735984.0, 75.0, 76.25, 74.5, 75.5)]
num=75.0 #whichever number

使用列表理解:

a=[ohlc.index(item) for item in ohlc if num in item]
print(a)

没有列表理解:

for item in ohlc:
   if num in item:
       print(ohlc.index(item))

输出:

0
2