简体   繁体   中英

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

From code I want to get index result = 1 but i cant do this.

Thank you.

Do you want something like

[idx for idx,o in enumerate(ohlc) if o[0]==735982.0][0]

> 1

PS Make sure you add a try/catch in case the element does not exist in the list

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM