python - Python 3 中的用户输入和排序列表

标签 python python-3.x list sorting input

我需要帮助来生成这样的输出:

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/

相关文章:

python - 具有不同形状的 Tensorflow 数据集

c++ - 加速一个长的 python 代码,该代码被证明仅由于单个 block 而变慢

python - 用可能的多个单词匹配州和城市

excel - 如何比较 COUNTIF 中的文字

python - Slack API - 来自自定义机器人帖子的附件作为纯文本

python - 如何将欧元货币字符串转换为 float ?

python - 安装Python 3.8.1 --with-openssl --without-root/apt/yum

python - 如何从列表中随机选择一个项目?

python - 更改列表中的值 - python

python - 应用 PyTorch CrossEntropy 方法进行多类分割