简体   繁体   English

如何在列表中找到列表的索引

[英]How to find the index of a list within a list

Basically I have a txt file thats an ouput from a fortran model. 基本上我有一个txt文件,它是来自fortran模型的输出。 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. 每个步骤都会添加如上所述的另一组内容,因此最终我有了一个包含3000多个步骤的txt文件。

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. 我正在尝试编写一些东西来索引“ Temp(K)”出现的所有点,然后将1加到该索引以获取实际温度的位置。

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. 因此,显然这不是最优雅的方式,但是我非常喜欢python。 So how do I find the index of a list within list(main2) if the first value of that list=='Temp(K)'? 那么,如果该列表的第一个值=='Temp(K)',我如何在list(main2)中找到列表的索引?

Nb. 铌。 I'm using np and matplot to plot the data after this. 我在这之后使用np和matplot绘制数据。

This can be done using python's enumerate() function. 这可以使用python的enumerate()函数来完成。

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 : 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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