python - 递归只打印一个列表

标签 python list recursion binary compression

在下面的代码中,我返回给定字符串中连续数字数量的整数值。

def consecutive_length(S):
    if S == '':
        return 0
    if len(S) == 1:
        return 1
    if S[0] == S[1]:
        return 1 + consecutive_length(S[1:])
    return 1

def compress(S):
    if S == '':
        return 0
    cons_length = consecutive_length(S)
    return [cons_length] + [compress(S[cons_length:])]

当我运行此打印语句时,将返回以下内容:

>>> print (compress('1111000000001111000111111111111111'))
[4, [8, [4, [3, [15, 0]]]]]

我真正希望返回以下内容:

>>> print (compress('1111000000001111000111111111111111'))
[4, 8, 4, 3, 15]

最佳答案

您的方法的替代方法是使用itertools.groupby():

from itertools import groupby

s = '1111000000001111000111111111111111'
answer = [len([digit for digit in group[1]]) for group in groupby(s)]
print(answer)

输出

[4, 8, 4, 3, 15]

关于python - 递归只打印一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35880149/

相关文章:

python - Flask Social - FACEBOOK_SOCIAL 不接受 request_token_params 参数

javascript - 递归函数和removeEventListener

Python:带有 pytz 时区标志的奇怪行为

python - pexpect 和 ssh : how to format a string of commands after su - root -c

python - 如何使用 Python 订阅 Websocket API channel ?

python - 如何从一个列表中获取一个值并将其应用于另一列表中的所有值

python - 查找最大数 <= 其他一些数

Python:如何从列表中删除空列表?

PHP FTP 递归目录列表

Javascript 递归函数不返回值?