python - 在python中查找数组中的索引

标签 python indexing

我看过 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/

相关文章:

sql - 当 IN 子句有子查询时,为什么 SQL Server 执行群集扫描?

python - Django表单和html表单有什么区别

python - 如何使用 tensorflow 有效地提取给定长度的所有切片

python - 无效的 URL '' : No schema supplied. 也许您的意思是 http ://?

python - 在我将 2D 灰度 PIL 图像转换为 1D numpy 数组后,获得 2D numpy 数组(图像/矩阵)的最平滑方法是什么?

python - 使用 while 循环查找输入数字的平均值并使用 break 语句退出循环的程序

node.js - Mongoose 不创建索引

python - 在 Python 中使用名称中带有字符串和迭代索引的 savefig

mysql - 在 MySQL 中使用 ALTER TABLE 建立索引需要多长时间?

python - 使用 `loc` 进行 Pandas bool 选择并不总是更快?