![](/img/trans.png)
[英]How can I iterate through two User Inputs and put them in a new variable with Python?
[英]How do I create an array of strings through user inputs and print them lexicographically in 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']
问题是列表上的+=
是两个列表的串联..因此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)
添加到列表的最佳方法是使用.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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.