gpt4 book ai didi

python - 在Python函数中使用递归输出元组列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:02 25 4
gpt4 key购买 nike

我对Python非常陌生,非常感谢任何帮助。基本上我输入一个字符串并返回“编码”的字符串(如果您愿意)。但是我的功能有问题,我不知道哪里出了问题。

def encode_it(x):
output = []
counter = 1
while x[0] != x[-1]:
if x[0] == x[1]:
counter += 1
return encode_it(x[1:])
else:
output += (x[0],counter)
counter = 1
return encode_it(x[1:])

return output

我想要的结果是这样的:

>>>encode_it("qqqqppttyl")
[("q",4),("p",2),("t",2),("y",1),("l",1)]

我真的很感激任何帮助,我只是在学习Python并尝试递归,如果有一种更简单的方法可以在不使用递归的情况下完成此操作,我将非常感激:)

谢谢大家!!为了响应 L3viathan 的代码,我修改了它,以便它输出结果,但它不会将最后一个字符添加到列表中:

def encode_it(x):
last_char = None
num = 0
result = []
for char in x:
t = ( )
if last_char == char:
num += 1
else:
if last_char:
t += last_char,num
result += t
last_char = char
num = 1
return result

如果我调用encode_it("qqqeerrw"),我会得到的结果是:

['q', 3, 'e', 2, 'r', 2] #it's leaving out the w here?

另外,我有一个空元组“t”和一个空列表“结果”的原因是,我希望每个字符都位于其自己的元组及其计数中......就像这样:

[("q",3),("e",2),("r",2),("w",1)]

最佳答案

这个任务很容易由 itertools.groupby 完成:

def encode_it(txt):
return ((c, len(tuple(grp))) for c, grp in itertools.groupby(txt))

然后:

>>> list(encode_it("qqqqppttyl"))
[('q', 4), ('p', 2), ('t', 2), ('y', 1)]

关于python - 在Python函数中使用递归输出元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36046760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com