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

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

如何通過(guò)用戶輸入創(chuàng)建字符串?dāng)?shù)組并在 Python 中按字典順序打印它們?

如何通過(guò)用戶輸入創(chuàng)建字符串?dāng)?shù)組并在 Python 中按字典順序打印它們?

拉丁的傳說(shuō) 2021-11-02 15:02:47
我正在嘗試創(chuàng)建一個(gè)小程序,提示用戶輸入 3 個(gè)單詞,然后將輸入的字符串放入數(shù)組,然后按字典順序?qū)?shù)組進(jìn)行排序并將數(shù)組打印為字符串列表。我嘗試過(guò) .sort 函數(shù),但它不起作用。我正在從事的項(xiàng)目不需要循環(huán)知識(shí)(我還沒(méi)有很多經(jīng)驗(yàn))。    a = []    first = input("Type a word: ")    second = input("Type another word: ")    third = input("Type the last word: ")    a += first    a += second    a += third    a = sorted(a)    print(a)我希望打印的結(jié)果是用逗號(hào)分隔的 3 個(gè)單詞 Apple, Banana, Egg相反,我的代碼打印 ['A', 'B', 'E', 'a', 'a', 'a', 'e', 'g', 'g', 'l', 'n', 'n', 'p', 'p']
查看完整描述

3 回答

?
弒天下

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

問(wèn)題是+=在一個(gè)列表上是兩個(gè)列表的串聯(lián)......所以python將你的字符串“Apple”解釋為(解壓的)列表['A', 'p', 'p', 'l', 'e']。


兩種不同的解決方案:


1) 將輸入變成一個(gè)包含單詞的列表:


a = []

first = input("Type a word: ")

second = input("Type another word: ")

third = input("Type the last word: ")

a += [first]

a += [second]

a += [third]


a = sorted(a)


print(a)

或者


2) 只需使用該append方法,該方法需要一個(gè)元素。


a = []

first = input("Type a word: ")

second = input("Type another word: ")

third = input("Type the last word: ")

a.append(first)

a.append(second)

a.append(third)


a = sorted(a)


print(a)


查看完整回答
反對(duì) 回復(fù) 2021-11-02
?
慕姐8265434

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

添加到列表的最佳方法是使用 .append


在你的情況下,我會(huì)這樣做:


a = []


first = input("Type a word: ")

second = input("Type another word: ")

third = input("Type the last word: ")


a.append(first)

a.append(second)

a.append(third)


print(sorted(a))

完成將數(shù)字添加到數(shù)組(在 python 中稱為列表)后,只需使用該sorted()方法按字典順序?qū)卧~進(jìn)行排序!


查看完整回答
反對(duì) 回復(fù) 2021-11-02
?
阿波羅的戰(zhàn)車(chē)

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

與其將輸入詞添加到列表中,不如將其附加。當(dāng)您將字符串添加到列表中時(shí),它會(huì)將字符串分解為每個(gè)字符,然后將其添加。因?yàn)槟荒軐⒁环N類(lèi)型的數(shù)據(jù)添加到另一種類(lèi)型(與不能添加“1”+3 一樣,除非它是 JS 但它完全不同)。


因此,您應(yīng)該附加單詞,然后使用 {}.sort() 方法對(duì)列表進(jìn)行排序并將其連接成一個(gè)字符串。


a = []


first = input("Type a word: ")

second = input("Type another word: ")

third = input("Type the last word: ")


a.append(first)

a.append(second)

a.append(third)


a.sort()

finalString = ','.join(a)


print(finalString)


查看完整回答
反對(duì) 回復(fù) 2021-11-02
  • 3 回答
  • 0 關(guān)注
  • 234 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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