[英]How to get an index of list?
>>> 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,但我不能这样做。
谢谢。
你想要类似的东西吗
[idx for idx,o in enumerate(ohlc) if o[0]==735982.0][0]
> 1
PS确保在列表中不存在该元素的情况下添加try / catch
您的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
索引是元素在列表中的位置。 您也可以使用index查找元素。 像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)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.