Reputation: 531
>>> 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
From code I want to get index result = 1 but i cant do this.
Thank you.
Upvotes: 0
Views: 75
Reputation: 16081
Your ohlc
list is a list of tuple. So you have to give tuple to find the index value like this.
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 is the position of a element in list. You can find the element using index also. Like ohlc[1]
. It return the corresponding element.
If you want to find the index value with the 735982.0
float value you can implement like this.
In [3]: [i[0] for i in ohlc].index(735982.0)
Out[2]: 1
But always better to use enumerate
to find the index value.
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)
Upvotes: 1
Reputation: 28277
ohlc
is a list of tuples so,
You may do something like this to match only the first element of the tuples:
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)
To search in all:
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
With list comprehension:
a=[ohlc.index(item) for item in ohlc if num in item]
print(a)
Without list comprehension:
for item in ohlc:
if num in item:
print(ohlc.index(item))
Output:
0
2
Upvotes: 1
Reputation: 795
Do you want something like
[idx for idx,o in enumerate(ohlc) if o[0]==735982.0][0]
> 1
P.S. Make sure you add a try/catch in case the element does not exist in the list
Upvotes: 1