第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

如何用給定的條件交換字符串的字符?

如何用給定的條件交換字符串的字符?

寶慕林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)我正在傳遞一個(gè)字符串示例列表["abcd", "bcad"]。對于每個(gè)字符串,i將i用j字符 if交換第 th 個(gè)字符(i+j)%2 == 0。我的代碼超出了字符串的邊界。請建議我一個(gè)更好的方法來解決這個(gè)問題
查看完整描述

2 回答

?
臨摹微笑

TA貢獻(xiàn)1982條經(jīng)驗(yàn) 獲得超2個(gè)贊

這是我的做法:


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"]))

定義一個(gè)對單個(gè)列表元素 ( password_single) 進(jìn)行操作的函數(shù)。這樣更容易開發(fā)和調(diào)試。在這種情況下,我將其設(shè)為內(nèi)部函數(shù),但并非必須如此。

使用三參數(shù)range調(diào)用,因?yàn)樗c執(zhí)行二參數(shù) +if(index%2 == 0)

將字符串轉(zhuǎn)換為列表,執(zhí)行交換并轉(zhuǎn)換回來。

使用“交換”類型的操作而不是兩個(gè)replaces。


查看完整回答
反對 回復(fù) 2021-07-13
  • 2 回答
  • 0 關(guān)注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號