简体   繁体   中英

How to get index of element in list of lists

I'm very new to python and I'm trying to get the index of an element in a list of lists. There goes my list:

 Data = [['0', '999.8', '1.78e-3'], ['5', '1000', '1.52e-3'], ['10', '999.7', '1.31e-3'], ['15', '999.1', '1.14e-3'], ['20', '998.2', '1.00e-3'], ['25', '997.0', '0.89e-3'], ['30', '995.7', '0.80e-3'], ['40', '992.2', '0.65e-3']]

I want to find the index of'10'. There is my code:

    for element in data:
            for e in element:
                index_valeur = e.index('10')
                print(index_valeur)

It doesn't seem to work and this is the error message:

ValueError: substring not found

How can I get the index of the value?

Pythonic best way is to use Pandas, my RAW attempt;-)

import numpy as np
import pandas as pd
import io
mycsv = '''
T,rho,mu
0,999.8,1.78e-3
5,1000,1.52e-3
10,999.7,1.31e-3
15,999.1,1.14e-3
20,998.2,1.00e-3
25,997.0,0.89e-3
30,995.7,0.80e-3
40,992.2,0.65e-3
'''
myNum = float(input("Enter number: "))
df = pd.read_csv(io.StringIO(mycsv))
print(sorted(df['T'].values.tolist(), key= lambda x:abs(x-myNum))[: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