简体   繁体   English

Python递归以向后打印列表中的项目

[英]Python recursion to print items from a list backwards

Using Python, I'm trying to read a list or strings backwards. 我正在尝试使用Python向后读取列表或字符串。 When finding the item of interest, I want to print all of those items from that point to the end of the list. 当找到感兴趣的项目时,我要打印从该点到列表末尾的所有那些项目。 I can do this without recursion and it works fine, but I feel like there's a nicer way to do this with recursion. 我可以不用递归来做到这一点,而且效果很好,但是我觉得有一种更好的递归方法。 :) :)

Example without recursion: 没有递归的示例:

items = ['item1', 'item2', 'item3', 'item4', 'item5']

items_of_interest = []
items.reverse()
for item in items:
    items_of_interest.append(item)
    if item == 'item3':
        break
    else:
        continue

items_of_interest.reverse()
print items_of_interest
['item3', 'item4', 'item5']

Update: 更新:

To add clarity to the question, the list is actually the output of a grep of a set of strings from a log file. 为了使问题更清楚,该列表实际上是日志文件中一组字符串的grep的输出。 The set of strings may be repeating and I only want the last set. 这组字符串可能会重复,我只想要最后一组。

Recursion wouldn't make this simpler, it would make it more complicated. 递归不会使它变得更简单,而会使它变得更复杂。

for i, item in enumerate(reversed(items), 1):
    if item == 'item3':
        items_of_interest = items[-i:]
        break
else:
    # 'item3' wasn't found

seems to be the simplest efficient way to do this to me. 对我来说,这似乎是最简单有效的方法。 You only have to iterate over the list from the end to 'item3' , since reversed returns an iterator. 您只需要从末尾遍历列表到'item3' ,因为reversed返回一个迭代器。

Edit: if you don't mind iterating over the whole list to create a reversed version, you can use: 编辑:如果您不介意遍历整个列表以创建反向版本,则可以使用:

i = list(reversed(items)).index('item3')
items_of_interest = items[-i-1:]

which is even simpler. 这更简单。 It raises an error if 'item3' isn't in the list. 如果'item3'不在列表中, 'item3'引发错误。 I'm using list(reversed()) instead of [:] then reverse() because it's one iteration over the list instead of two. 我使用list(reversed())而不是[:]然后使用reverse()因为它是列表的一次迭代,而不是两次。

Edit 2: Based on your comment to the other answer, my first version does what you want -- searches for the item from the end without iterating over the whole list. 编辑2:根据您对其他答案的评论,我的第一个版本可以满足您的要求-从头开始搜索项目,而无需遍历整个列表。 The version in the question has to iterate the list to reverse it, as does my second version. 问题中的版本必须迭代列表以将其反转,就像我的第二个版本一样。

A minimally modified, but more efficient, version of your original would be: 对原始文档进行最小程度修改但更有效的版本是:

items_of_interest = []
for item in reversed(items):
    items_of_interest.append(item)
    if item == 'item3':
        break
items_of_interest.reverse()

A recursive solution is not called for here. 这里不要求递归解决方案。 To the problem of finding the slice of a list from the last occurrence of a item to the end of the list, one approach is to define an auxiliary function 对于从项目的最后一次出现到列表末尾查找列表切片的问题,一种方法是定义辅助功能

>>> def rindex(s, x):
...     for i, y in enumerate(reversed(s)):
...         if x == y:
...             return -i-1
...     raise ValueError
... 
>>> items[rindex(items, "b"):]
['b', 'f']

The auxiliary function can be called rindex because Python has a rindex method to find the last occurrence of a substring in a string. 辅助函数可以称为rindex因为Python具有rindex方法来查找字符串rindex字符串的最后一次出现。

If you must do it recursively (perhaps it is homework) then think about it as in this pseudocode (not yet worked out completely) 如果您必须递归执行(也许是家庭作业),则可以按照此伪代码来考虑(尚未完全解决)

def tail_from(list, x):
    return tail_from_aux(list, x, [])

def tail_from_aux(list, element, accumulated):
    if list is empty:
        return []
    elif list ends with element
        return element::accumulated
    else:
        last = list[-1]
        return tail_from_aux(list[:-1], element, last::accumulated)

But, this is memory-intensive, goes through the whole list (inefficient), and is not Pythonic. 但是,这是内存密集型的,会遍历整个列表(效率低下),并且不是Pythonic。 It may be appropriate for other languages, but not Python. 它可能适用于其他语言,但不适用于Python。 Do not use. 不使用。

Since your actual question refers to files, and log files at that, you may not be able to reduce this problem to an array search. 由于您的实际问题是关于文件的,而在那儿是日志文件,因此您可能无法将此问题归结为数组搜索。 Therefore, check out Read a file in reverse order using python , there are some interesting answers there as well as some links to follow. 因此,签出使用python反向读取文件 ,那里有一些有趣的答案以及一些链接。

Consider mixing tac with awk and grep if you are able to as well. 如果可以,请考虑将tacawkgrep混合。

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

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