猿问

如何通过用户输入创建字符串数组并在 Python 中按字典顺序打印它们?

我正在尝试创建一个小程序,提示用户输入 3 个单词,然后将输入的字符串放入数组,然后按字典顺序对数组进行排序并将数组打印为字符串列表。


我尝试过 .sort 函数,但它不起作用。我正在从事的项目不需要循环知识(我还没有很多经验)。


    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)

我希望打印的结果是用逗号分隔的 3 个单词


 Apple, Banana, Egg

相反,我的代码打印


 ['A', 'B', 'E', 'a', 'a', 'a', 'e', 'g', 'g', 'l', 'n', 'n', 'p', 'p']


拉丁的传说
浏览 209回答 3
3回答

弑天下

问题是+=在一个列表上是两个列表的串联......所以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)

慕姐8265434

添加到列表的最佳方法是使用 .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()方法按字典顺序对单词进行排序!

阿波罗的战车

与其将输入词添加到列表中,不如将其附加。当您将字符串添加到列表中时,它会将字符串分解为每个字符,然后将其添加。因为您不能将一种类型的数据添加到另一种类型(与不能添加“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)
随时随地看视频慕课网APP

相关分类

Python
我要回答