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

How to swap Character of string with the given condition?

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+j)%2 == 0i 会将第 i 个字符与 j 个字符交换。 我的代码超出了字符串的边界。 请建议我一个更好的方法来解决这个问题

字符串在 python 中是不可变的,因此您不能就地交换字符。你必须建立一个新的字符串。

此外,您的代码不适用于 passlist 中的每个字符串。您在第一个 for 块中遍历 passlist 中的字符串,然后在该块外部使用 temp 变量。这意味着第二个 for 循环只迭代最后一个字符串。

现在,做你想做的事情的方法可能是:

for i in range(len(passlist)):
    pass_ = passlist[i]
    new_pass = [c for c in pass_] # convert the string in a list of chars
    for j in range(len(pass_) / 2):
        new_pass[j], new_pass[j+2] = new_pass[j+2], new_pass[j] # swap

    listt.append(''.join(new_pass)) # convert the list of chars back to string

这是我的做法:

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)
  • 相同
  • 将字符串转换为列表,执行交换并转换回来。
  • 使用 "swap" 类型的操作而不是两个 replaces。