简体   繁体   English

如何获取python枚举中的项()

[英]How to get to an item in a python enumerate()

I'm new to python. 我是python的新手。

I have two files, one that contains symbols (words) and another that is a map file. 我有两个文件,一个包含符号(单词),另一个是地图文件。

Both files are text files. 这两个文件都是文本文件。 The map file does contain form feeds. 地图文件确实包含换页符。

I want to find the line in the map file that is one above the line that contains a symbol in the map file. 我想在地图文件中找到一行,该行位于地图文件中包含符号的行上方。

I have the following code. 我有以下代码。

Osymbolfile="alistofsymbols"
mapfile="amapfile"
maplines = (line.rstrip('\n\f') for line in open(mapfile))
for line in Osymbolfile:
    line = (line.rstrip('\n') )
    print "line= ",line
    linecount = 0
    for index, scanline in enumerate(maplines):
        if line in scanline:
            print "scanline=",scanline
            print "index=",index
        else:
            linecount = linecount + 1
    print "= ",linecount

After print "index=",index ,I've tried print maplines[index-1] , but I get an error. print "index=",index ,我尝试print maplines[index-1] ,但是我收到错误。

How do I obtain the line above the index 'th line in maplines ? 如何获得上述线路index日线中的” maplines

Your maplines object is a generator expression ; 你的maplines对象是一个生成器表达式 ; these produce items on demand and are not indexable. 这些产品按需生产,不可转化。

You could use a list comprehension instead: 你可以改用列表理解:

maplines = [line.rstrip('\n\f') for line in open(mapfile)]

Now you have a indexable list object instead. 现在你有了一个可索引的列表对象。 Even better, you can now loop over this object multiple times; 更好的是,您现在可以多次遍历此对象; you cannot do that with a generator. 你不能用发电机做到这一点。

The proper way to handle your case however, is to store the previous line only: 但是,处理案例的正确方法是仅存储前一行

with open(mapfile) as maplines:
    prev = None
    for line in maplines:
        if something in line:
            return prev
        prev = line

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

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