我正在尝试创建一个小程序,提示用户输入 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']
最佳答案
问题是列表上的 +=
是两个列表的串联..因此 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)
关于python - 如何通过用户输入创建一个字符串数组并在 Python 中按字典顺序打印它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54584283/