简体   繁体   中英

How to find the index of a list within a list

Basically I have a txt file thats an ouput from a fortran model. The output looks a little like this:

Title:Model

Temp(K)    Ionic str    Rho    Phi    H2O    Ice ...
273.15     4            1.003  1.21   1000   0.00

Species    Ini Conc    Final Conc     Act ....
H          0.0         0.12032        0.59
NH4        3.0         3.00           0.43
Cl         1.0         1.00           0.47
...

Title:Model

Temp(K)    Ionic str    Rho    Phi    H2O    Ice ...
273.15     4            1.003  1.21   1000   0.00

Species    Ini Conc    Final Conc     Act ....
H          0.0         0.12032        0.59
NH4        3.0         3.00           0.43
Cl         1.0         1.00           0.47
...

Each step adds another set like the above so eventually I have a txt file with 3000+ steps.

So I want to recall all the temperatures at each step. I'm trying to write something to index all the points where 'Temp(K)' appears and then add 1 to that index to get the location of the actual temperature.

My code looks like this:

import numpy as np
import matplotlib.pyplot as plt
main=[]
main2=[]
count=0
with open('FrOut.txt', 'r') as f:
    data=f.readlines()
    for line in data:
        main.append(line.split(','))
for value in main:
    for x in value:
        main2.append(x.split())
for value in main2:
    for x in value:
            if x=='Temp(K)':count+=1

So obviously this isn't the most elegant way but I'm very much in the deep end with python. So how do I find the index of a list within list(main2) if the first value of that list=='Temp(K)'?

Nb. I'm using np and matplot to plot the data after this.

This can be done using python's enumerate() function.

Here's an example of extracting the indexes. (And, just for fun, the temperatures Too!)

idxs = []
tempature_values = []
for idx, value in enumerate(main2):
    # Check if value is not empty & the first element is 'Temp(K)'
    if value and value[0] == 'Temp(K)':
        idxs.append(idx)
        temp_values.append(main2[idx+1][0])

How about this:

temp_rows = []

with open(f, 'rb') as fin:
    reader = csv.reader(fin)
    for index, row in enumerate(reader):
        if 'Temp(K)' in [word for words in row for word in words.split()]:
            temp_rows.append(index)

Read the file into a list.

with open('FrOut.txt', 'r') as f:
    data=f.readlines()

Get the numbers of the lines that start a temperature (using a list comprehension because it is fast):

idx = [n+1 for n, ln in enumerate(data) is ln.startswith('Temp(K)']

Get the temperatures, again with a list comprehension.

temps = [float(data[n].split()[0]) for n in idx]

If desired, you could even combine this into one list comprehension:

temps = [float(data[n+1].split()[0]) for n, ln in enumerate(data) if ln.startswith('Temp(K)')]

An example in IPython :

In [1]: text = '''Title:Model
   ...: 
   ...: Temp(K)    Ionic str    Rho    Phi    H2O    Ice ...
   ...: 273.15     4            1.003  1.21   1000   0.00
   ...: 
   ...: Species    Ini Conc    Final Conc     Act ....
   ...: H          0.0         0.12032        0.59
   ...: NH4        3.0         3.00           0.43
   ...: Cl         1.0         1.00           0.47
   ...: ...
   ...: 
   ...: Title:Model
   ...: 
   ...: Temp(K)    Ionic str    Rho    Phi    H2O    Ice ...
   ...: 273.15     4            1.003  1.21   1000   0.00
   ...: 
   ...: Species    Ini Conc    Final Conc     Act ....
   ...: H          0.0         0.12032        0.59
   ...: NH4        3.0         3.00           0.43
   ...: Cl         1.0         1.00           0.47
   ...: ...
   ...: '''

In [2]: data = text.splitlines()

In [3]: idx = [n+1 for n, ln in enumerate(data) if ln.startswith('Temp(K)')]

In [4]: idx
Out[4]: [3, 14]

In [5]: [float(data[n].split()[0]) for n in idx]
Out[5]: [273.15, 273.15]

In [6]: [float(data[n+1].split()[0]) for n, ln in enumerate(data) if ln.startswith('Temp(K)')]
Out[6]: [273.15, 273.15]

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