为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2021-07-08 18:49:49
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。我的代码超出了字符串的边界。请建议我一个更好的方法来解决这个问题
查看完整描述

2 回答

?
临摹微笑

TA贡献1982条经验 获得超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。


查看完整回答
反对 回复 2021-07-13
  • 2 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信