Python 列表理解从列表中删除元素和下一个元素

Python list comprehension remove element and next element from list

我想使用列表理解从字符列表中删除所有出现的“\x08”(退格字符)我还想删除“\x08”之前的字符。

我结束了一个递归函数调用,但如果有一个 可读/pythonic one liner 就好了。

示例输入:

['a', 't', '+', 'B', 'A', 'D', '\x08', '\x08', '\x08','c', 'o', 'p', 's', '=', '?']

期望的输出:

['a', 't', '+', 'c', 'o', 'p', 's', '=', '?']

以防人们想看到我当前的解决方案。

def line_parser(self,line):
    if '\x08' in line:
        del line[line.index('\x08') -1]
        del line[line.index('\x08')]
        self.line_parser(line)
    else:
        self.something_else(line)

这是一个 Pythonic 解决方案:

>>> data = ['a', 't', '+', 'B', 'A', 'D', '\x08', '\x08', '\x08','c', 'o', 'p', 's', '=', '?']
>>> newdata = []
>>> for c in data:
...     if c == '\x08' and newdata:
...         newdata.pop()
...     else:
...         newdata.append(c)
...
'D'
'A'
'B'
>>> newdata
['a', 't', '+', 'c', 'o', 'p', 's', '=', '?']
>>>

它可读、明确,并利用了 Python list 的性能特征。 Pythonic并不是"one-liner"的同义词,事实上,往往单行解法是Pythonic的反义词。