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)

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)行排序!

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)
添加回答
舉報(bào)