Search index in array in python

I looked up the index search of the item specified in the list containing it in Python

and I did not find a solution. I have a list that I added from 426 values, and I'm looking for the "KORD" index, but it claims to not be on the list when it is.

metar_txt = open("metar.txt", "r") 
lines = metar_txt.readlines() 
for line in lines: 
    if len(line) > 20: 
        stations = []
        stations.append(line.split(' ')[0])
        print stations.index('KORD')
metar_txt.close()

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-9271d129d452> in <module>()
      5         stations = []
      6         stations.append(line.split(' ')[0])
----> 7         print stations.index('KORD')
      8 metar_txt.close()

ValueError: 'KORD' is not in list
+4
source share
2 answers

create a list outside the loop, you save only one item in your list, because the stations = []loop continues to create an empty list, and then you add one item, repeating each iteration:

stations = []
for line in lines: 
    if len(line) > 20:

, , , , , , , , , :

with open("metar.txt", "r")  as metar_txt:
    stations = []
    for line in metar_txt: 
        if len(line) > 20: 
            stations.append(line.rstrip().split(' ')[0]
    print stations.index('KORD') # outside loop

, , , , , , if len(line) > 20 True, , :

with open("metar.txt", "r")  as metar_txt:
    stations = []
    i = 0
    for line in metar_txt:
        if len(line) > 20:
            w = line.rstrip().split(' ')[0]
            if w == "KORD":
                print(i)
            i += 1

, , dict, 0 (1):

with open("metar.txt", "r")  as metar_txt:
    stations = {}
    i = 0
    for line in metar_txt:
        if len(line) > 20:
            w = line.rstrip().split(' ')[0]
            stations[w] = i
            i += 1
print(stations["KORD"])

, OrderedDict:

from collections import OrderedDict
with open("metar.txt", "r")  as metar_txt:
    stations = OrderedDict()
    i = 0
    for line in metar_txt:
        if len(line) > 20:
            w = line.rstrip().split(' ')[0]
            stations[w] = i
            i += 1

, for st in stations:print(st) , stations["word"] .

genxp str.partition, :

from collections import OrderedDict
with open("metar.txt", "r")  as metar_txt:
 lines = (line.partition(' ')[0] for line in metar_txt if len(line) > 20)
 stations = OrderedDict((el, idx) for idx, el in enumerate(lines))

itertools.count xp:

with open("metar.txt", "r")  as metar_txt:
    from itertools import count
    cn = count()
    stations = OrderedDict((line.rstrip().split(' ')[0], next(cn))
                           for line in metar_txt if len(line) > 20)
+4

.

-1

Source: https://habr.com/ru/post/1608236/


All Articles