如何用给定的条件交换字符串的字符?

def password(passlist):


    listt = []

    for i in range(0, len(passlist)):

        temp = passlist[i]


    for j in range(0, len(temp)/2):

        if((j+2)%2 == 0) :

                t = temp[j]

                temp.replace(temp[j], temp[j+2])

                temp.replace(temp[j+2], t)  

    listt.append(temp)

我正在传递一个字符串示例列表["abcd", "bcad"]。对于每个字符串,i将i用j字符 if交换第 th 个字符(i+j)%2 == 0。我的代码超出了字符串的边界。请建议我一个更好的方法来解决这个问题


宝慕林4294392
浏览 148回答 2
2回答

临摹微笑

这是我的做法:def password(passlist):    def password_single(s):        temp = list(s)        for j in range(0, len(temp) // 2, 2):            temp[j], temp[j+2] = temp[j+2], temp[j]        return ''.join(temp)    return [password_single(s) for s in passlist]print(password(["abcd", "bcad"]))定义一个对单个列表元素 ( password_single) 进行操作的函数。这样更容易开发和调试。在这种情况下,我将其设为内部函数,但并非必须如此。使用三参数range调用,因为它与执行二参数 +if(index%2 == 0)将字符串转换为列表,执行交换并转换回来。使用“交换”类型的操作而不是两个replaces。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python