gpt4 book ai didi

python - 为什么我在下面的代码中没有得到任何输出?

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:39 28 4
gpt4 key购买 nike

编译代码时没有错误。我将函数调用为:pattern('abc')。期望输出为 'A-Bb-Ccc'

def pattern(s):
v = []
v = list(s)
strlen = len(v)
i = 0
cntr = 0
strng = []
while i < strlen:
j = 0
while j <= i:
if j == 0:
strng.append(v[i].upper())
else:
strng.append(v[i])
j += 1
strng.append('-')
i += 1
z = ''.join(strng)
return z

最佳答案

UPDATE 使用 enumerate 而不是 zip

source = 'abc'

'-'.join([(x*i).capitalize() for i, x in enumerate(source, 1)])

source = 'abc'

'-'.join([(x*i).capitalize() for x,i in zip(source, range(1, len(source)+1))])

一些解释:

zip(source, range(1, len(source)+1)) 创建对 (a,1), (b,2), (c,3)

x*i 表示连接,即 a*3 生成字符串 aaa

aaa.capitalize() 使首字母大写

'-'.join(a_list) 使用 - 作为分隔符连接 a_list 中的元素

关于python - 为什么我在下面的代码中没有得到任何输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38568970/

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