Python 在递归中只打印一个列表
在下面的代码中,我返回给定字符串中连续数字数量的整数值Python 在递归中只打印一个列表,python,list,recursion,binary,compression,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 == '': retu
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]
我真的希望返回以下内容:
>>> print (compress('1111000000001111000111111111111111'))
[4, [8, [4, [3, [15, 0]]]]]
>>> print (compress('1111000000001111000111111111111111'))
[4, 8, 4, 3, 15]
另一种方法是使用
itertools.groupby()
:
输出
[4, 8, 4, 3, 15]
当您返回一个列表时,
[返回的内容]
将是一个嵌套列表,但当您返回一个整数时,它将只是一个列表。相反,(在compress()
)中,始终返回一个列表,并在使用它返回的内容时删除括号:
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 []
cons_length = consecutive_length(S)
return [cons_length] + compress(S[cons_length:])
给你:
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 []
cons_length = consecutive_length(S)
return [cons_length] + compress(S[cons_length:])
取出
[compress(S[cons_length:])]
@zondo中的括号如果我这样做,我会得到一个错误,说TypeError:只能将list(而不是“int”)连接到list
啊,是的。无论如何都要这样做,但在任何情况下,如果您要返回一个整数(例如返回0
),请将其更改为返回一个列表:返回[0]
@zondo如果您做出正式的回答,我将接受它。非常感谢。我认为您实际上想要返回[]