为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉丁的传说 2021-11-02 15:02:47
我正在尝试创建一个小程序,提示用户输入 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']
查看完整描述

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)


查看完整回答
反对 回复 2021-11-02
?
慕姐8265434

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()方法按字典顺序对单词进行排序!


查看完整回答
反对 回复 2021-11-02
?
阿波罗的战车

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)


查看完整回答
反对 回复 2021-11-02
  • 3 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号