将部分列表传递给Python函数

时间:2013-02-18 20:20:16

标签: python

我正在编写一个Python程序来读取文本文件并提取一些信息。我正在尝试找到三个项目,一个实数和两个列表。该脚本将文本文件的行存储为列表inLines。在阅读这些行时,脚本使用for curLine in inLines:,然后在所有行中搜索特定键。一旦找到搜索键,我想将inLines的剩余部分传递给一个函数,再读几行,然后返回到函数停止的行的主脚本。

这是我想要发生的一个小图表(作为评论给出的代码说明)

line of text that doesn't matter    #Read by main, nothing interesting happens
line of text that doesn't matter    #Read by main, nothing interesting happens
search key A                        #Read by main, all following lines passed to function A
line that matters                   #Read by function A, stores in object
line that matters                   #Read by function A, stores in object

line that matters                   #Read by function A, stores in object


search key B                        #Read by function A, return to main, all following lines passed to function B


line that matters                   #Read by function B, stores in object

search key C                        #Read by function B, return to main, all following lines passed to function C
line that matters                   #Red by function C, stores in object

因此,每个搜索键告诉程序要处于哪个功能(并且不同的键可以按任何顺序)。当脚本找到键时,它会将所有其他行传递给正确的函数,并且每当函数找到搜索键时,它就会断开,并将所有其他行传递回main(然后将相同的行传递给相应的函数)< / p>

对于这个问题的书感到抱歉,我只是在经过多年的FORTRAN学习Python之后,所以如果有人能想出更好的方法来解决这个问题,我愿意接受建议。提前致谢

3 个答案:

答案 0 :(得分:1)

这个小脚本关闭到你想要的。它会丢弃在指定搜索功能之前出现的行。你应该能够根据自己的需要进行调整。

import sys


def search_func_a(l):
    """
    Called for things that follow `search key A`
    """
    print 'A: %s' % l


def search_func_b(l):
    """
    Called for things that follow `search key B`
    """
    print 'B: %s' % l


def search_key_func(l):
    """
    Returns the associated "search function" for each search string.
    """
    if 'search key A' in l:
        return search_func_a
    if 'search key B' in l:
        return search_func_b
    return None


def main():
    # Start with a default handler.  This changes as `search key` lines are
    # found.
    handler = lambda _: 0 

    for line in open('test.txt'):
        # search_key_func returns None for non `search key` lines.  In that
        # case, continue to use the last `search function` found.
        search_func = search_key_func(line) 
        if search_func:
            # If a search line is found, don't pass it into the search func.
            handler = search_func
            continue
        handler(line)


if __name__ == '__main__':
    sys.exit(main())

答案 1 :(得分:0)

做这样的事情有问题吗?

inA = inB = inC = False
for line in file:
  if keyA(line):
    inA = True
    inB = inC = False
  elif keyB(line):
    inB = True
    inA = inC = False
  elif keyC(line):
    inC = True
    inA = inB = False
  if inA:
    processA(line)
  if inB:
    processB(line)
  if inC:
    processC(line)

你在问是否有更快的方法?

答案 2 :(得分:0)

#!/usr/bin/env python3
# encoding: utf-8

import sys

def find(haystack, needle, start_line = 0):
    for i, line in enumerate(haystack[start_line:]):
        if line == needle:
            return i + 1
    raise("%s not found." % needle)

def main(argv = None):
    if argv is None:
        argv = sys.argv

    with open(argv[1], 'r') as f:
        text = f.read().splittext()

    find(text, "c", find(text, "b", find(text, "a")))

if __name__ == "__main__":
    sys.exit(main())

我不确定你的意思是“存储在对象中”,但代码很容易修改以适合你的目的。