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

标签 python arrays string list sorting

我正在尝试创建一个小程序,提示用户输入 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/

相关文章:

Python正则表达式获取一行文本中关键字前后的n个字符

c++ - System::对 C++ char* 参数的字符串引用

python - Django中post方法访问表单数据

python - 为什么我的 tkinter 应用程序会显示 node.js 窗口?

安装包成功后找不到Python包

c++ - Boost二进制序列化 - 固定长度错误的双数组

javascript - 将类似数组的字符串解析为数组

python - Pandas 在第一个 % 符号和第二个字母上拆分列

javascript - 在 Javascript 中使用 map 数组时未定义的值

php - 如何在 PHP 中创建一个函数,根据其中一个键对数组进行排序