【问题标题】:Reading ahead while looping through a list循环遍历列表时提前阅读
【发布时间】:2019-02-26 19:00:13
【问题描述】:

我有一个文本文件列表,如下所示:

page_text_list = ['.............', '.............','name: bill','name: bob','address: 123 main st','name : tim','address: 124' ,'main st','name:', '.......']

如果我在字符串中找到“名称:”,我想提前阅读以获取该名称的地址。但是,正如您所看到的,模式是不一致的,并且并不总是可以假设下一行包含完整地址。

我想用一个简单的循环遍历列表

for line in page_text_list:

但这似乎不适合这项工作。这里最好的方法是什么?

【问题讨论】:

  • 能否请您发布一个语法正确的 Python 列表?很难猜测您的实际数据结构是什么样的。我无法复制粘贴和玩弄我们目前拥有的东西。
  • 这是怎么回事.....
  • 您可以遍历iter(page_text_list) 并使用itertools.dropwhile 来修改迭代器,接下来会调用for 循环。如果没有给定列表的具体输出,我很难说更多。
  • 问题含糊不清。当一个地址直到另一个名字之后才跟在一个名字后面时,您的预期输出是什么?两个名字应该返回相同的地址,还是第一个什么都没有?请给出您的预期输出。

标签: python iterable


【解决方案1】:

使用基于列表范围的范围迭代器,如下所示:

for index in range(len(page_text_list)):
    if page_text_list[index].startswith('name'):
        do_lookahead(page_text_list[index+1:])

def do_lookahead(list_rest):
     for line in list_rest:
         if line.startswith('address'):
             return line

【讨论】:

    【解决方案2】:

    假设您想要获取 name: ... 行之后直到下一个 name: ... 行的所有行的列表,您可以这样做:

    from itertools import dropwhile, takewhile
    
    page_text_list = ['.............', '.............','name: bill','name: bob','address: 123 main st','name: tim','address: 124' ,'main st','name:', '.......']
    
    def get_address(name):
        # we drop all the lines who aren't 'name: bob'
        it = dropwhile(lambda line: line != "name: " + name, page_text_list)
    
        try:
            next(it)  # we drop the 'name: bob' line 
        except StopIteration: # if the name wasn't found, we exhausted the iterator
            pass
    
        # we return all the following lines, while they don't contain 'name:'
        return list(takewhile(lambda line:"name:" not in line, it))
    

    输出:

    print(get_address('bill'))  # no address
    # []
    
    print(get_address('dude'))  # not in our list
    # []
    
    print('\n'.join(get_address('tim')))
    # address: 124
    # main st 
    

    【讨论】:

      猜你喜欢
      • 2013-06-22
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2018-10-26
      • 2013-09-04
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多