我需要帮助来生成这样的输出:
1. Enter a member: samantha
Names: ['Samantha']
2. Enter a member: susan
Names: ['Samantha', 'Susan']
3. Enter a member: billy
Names: ['Billy', 'Samantha', 'Susan']
4. Enter a member: billy
4. Enter a member: samantha
4. Enter a member: Jason
Names: ['Billy', 'Jason', 'Samantha', 'Susan']
5. Enter a member:
Members:
1. Billy
2. Jason
3. Samantha
4. Susan
我已经努力创建一个程序来执行此操作,但无济于事。我将在代码本身的问题中发表评论。预先感谢您的帮助。
def function():
x = []
#a = "1." # I tried to number the questions by adding these but it doesnt work
while True:
#a += 1
name = input("Enter name: ").title()
x.append(name)
print("Names:", x)
#if name == name: # this condition is made so that an input that is typed in again doesn't get included in the list
#name = input("Enter name: ").title()
# where should I add an insert() here to have the list alphabetically ordered?
if not name: # pressing enter prints out the second half of the output, listing the members
#print("\nMembers:", x).sort()
break
function()
最佳答案
你做的几乎所有事情都是正确的,但问题是你在哪里打破了循环。您首先要附加名称,然后检查输入是否只是一个回车。因此,首先检查输入,然后将其附加到列表中。 这是我的代码:
def fun1():
l = []
while True:
s = input("Enter a member: ")
if not s:
break
l.append(s.title())
print("Names:", l)
l.sort()
print("Members:")
for i in range(0, len(l)):
print(i+1,end = '')
print(".", l[i])
fun1()
希望对您有所帮助。
关于python - Python 3 中的用户输入和排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301594/