我看过 Finding the index of an item given a list containing it in Python
我还没有找到解决办法。我有一个附加了 426 个值的列表,我正在寻找“KORD”的索引,但它声称它不在列表中,而实际上是这样。
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
最佳答案
在循环外创建列表,您仅将列表中的单个元素存储为 stations = []
在循环中不断创建一个空列表,然后添加一个元素,重复每次迭代:
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
最后,如果你想为多个单词保留一些索引记录,你可以使用字典,这样找到的索引将为 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"]
会给你索引。
或者像 Jon 评论的那样使用 genexp 和 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
使用单个 genexp:
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)
关于python - 在python中查找数组中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32683663/