Python 展平';下一个';和';上一个';链接列表中的链接
我有一个表示数据结构遍历的字符串列表。我想将链接列表遍历折叠成更紧凑的表示形式。为此,我想计算相邻Python 展平';下一个';和';上一个';链接列表中的链接,python,Python,我有一个表示数据结构遍历的字符串列表。我想将链接列表遍历折叠成更紧凑的表示形式。为此,我想计算相邻next和prev链接的数量,并将它们折叠成一个整数 以下是我想进行的转换示例: ['modules'] --> ['modules'] ['modules', 'next'] --> ['modules', 1] ['modules', 'prev']
next
和prev
链接的数量,并将它们折叠成一个整数
以下是我想进行的转换示例:
['modules'] --> ['modules']
['modules', 'next'] --> ['modules', 1]
['modules', 'prev'] --> ['modules', -1]
['modules', 'next', 'next', 'next', 'txt'] --> ['modules', 3, 'txt']
['modules', 'next', 'prev', 'next', 'txt'] --> ['modules', 1, 'txt']
['super_blocks', 'next', 's_inodes', 'next'] --> ['super_blocks', 1, 's_inodes', 1]
每个next
链接计数为+1,每个prev
链接计数为-1。相邻的next
s和prev
s相互抵消。他们可以按任何顺序来
对此,我有一个可行的解决方案,但我正在努力寻找一个令人满意的优雅的Pythonic解决方案。您可以使用发电机:
def links(seq):
it = iter(seq)
while True:
el = next(it)
cnt = 0
try:
while el in ['prev', 'next']:
cnt += (1 if el == 'next' else -1)
el = next(it)
finally:
if cnt != 0:
yield cnt
yield el
print list(links(['modules', 'next', 'prev', 'next', 'txt']))
值得注意的是,包含相同数量的
next
和prev
的序列将被完全删除。如果您想要更改代码以生成0
(我认为这方面的要求有点不清楚)。下面是想到的最简单的方法。直截了当是理解、调试和未来维护的宝贵品质
def process(l):
result = []
count = 0
keepCount = False
for s in l:
if s == "next":
count += 1
keepCount = True
elif s == "prev":
count -= 1
keepCount = True
else:
if keepCount:
result.append(count)
count = 0
keepCount = False
result.append(s)
# end if
# end for
if keepCount:
result.append(count)
return result
# end process()
不过,我更喜欢NPE使用发电机。(我的可以通过将'result.append()'更改为'yield'来轻松转换。)他的(原始)答案与我的答案几乎相同,但如果下一个/上一个标记的数量相等,我会将0计数包括在内。稍微减少一点怎么样 那么:
def convert(ls):
last = None
for x in ls:
if x == 'prev': x = -1
if x == 'next': x = +1
if isinstance(x, int) and isinstance(last, int):
x += last
elif last: # last is not None if you want zeroes
yield last
last = x
yield last
['modules'、'next'、'prev'、'txt']->失败。@unbeli:我认为这是一个很大的优势。这个角落的要求不清楚。我认为这很清楚,下一个/上一个应该是一个整数。对于这种情况和你的代码,他们不会同意。我没有指定0的大小写,因为我可以选择使用它,放置0或完全忽略它。@unbeli:请参阅上面OP的评论。它详细说明了要求。
def convert(ls):
last = None
for x in ls:
if x == 'prev': x = -1
if x == 'next': x = +1
if isinstance(x, int) and isinstance(last, int):
x += last
elif last: # last is not None if you want zeroes
yield last
last = x
yield last