3 回答

TA贡献1818条经验 获得超8个赞
问题是+=在一个列表上是两个列表的串联......所以python将你的字符串“Apple”解释为(解压的)列表['A', 'p', 'p', 'l', 'e']。
两种不同的解决方案:
1) 将输入变成一个包含单词的列表:
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方法,该方法需要一个元素。
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贡献1813条经验 获得超2个赞
添加到列表的最佳方法是使用 .append
在你的情况下,我会这样做:
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))
完成将数字添加到数组(在 python 中称为列表)后,只需使用该sorted()方法按字典顺序对单词进行排序!

TA贡献1862条经验 获得超6个赞
与其将输入词添加到列表中,不如将其附加。当您将字符串添加到列表中时,它会将字符串分解为每个字符,然后将其添加。因为您不能将一种类型的数据添加到另一种类型(与不能添加“1”+3 一样,除非它是 JS 但它完全不同)。
因此,您应该附加单词,然后使用 {}.sort() 方法对列表进行排序并将其连接成一个字符串。
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)
添加回答
举报