使用用户输入在列表中查找和替换(python)

1 投票
2 回答
1666 浏览
提问于 2025-04-28 11:26

我需要帮助,关于我作业的额外加分部分。这个任务的目标是先创建一个列表,然后让用户输入他们自己的数据(在这个例子中是鸟类),接着对这些鸟进行排序并返回结果。额外加分的部分是允许用户在之后编辑任何信息。我不知道怎么找到并替换用户输入的内容。

代码:

def sorted_list():
    bird_list.sort()
    for i in bird_list:
        print(i)
    print()
    print('There are', len(bird_list), 'birds in the list.')
    #end for
#end def

cond = 'y'

while cond == 'y':
    bird = input('Type the name of another bird (RETURN when finished): ')
    if bird in bird_list:
        print(bird, 'is already in the list.')
    else:
        bird_list.append(bird)
        print(bird, 'has been added to the list.')
    if bird == '':
        cond = 'n'
        sorted_list()
    #end if
#end while

edit = input('Edit? (y/n) ')

print()
if edit == 'y':
    change = input('Which bird would you like to change? ')
    if change == bird_list[0]:
        i = input('Enter correction ' )
    else:
        print('Entry not found in list')

编辑:

我用这个解决了编辑的问题

if edit == 'y':
    change = input('Which bird would you like to change? ')
    if change in bird_list:
        loc = bird_list.index(change)
        bird_list.remove(change)
        correction = input('Enter correction ' )
        bird_list.insert(loc, correction)
    else:
        print('Entry not found in list')
暂无标签

2 个回答

1

看起来你想根据鸟的名字找到它在列表中的位置。如果你想在Python的列表里找到一个特定的值,可以用 list.index 这个方法。想了解更多,可以查看 标准类型的文档

1

首先,你可以用 .index 来找出一个项目在列表中的位置。

但是你代码里还有另一个问题,这就是为什么当你输入一个本该在列表第一个位置的名字时,却得到了 'Entry not found on list' 的提示。原因是当你第一次输入一个空字符串(就是直接按下 Enter 键而什么都不输入)时,你在 bird_list 里添加了一个空字符串的鸟名。然后你的 sorted_list 方法把这个空字符串 '' 排到了列表的最前面,具体情况如下:

if bird in bird_list:
    print(bird, 'is already in the list.')
# if bird is ''(first time), it will be appended to the list, too
else:
    bird_list.append(bird)
    print(bird, 'has been added to the list.')
if bird == '':
    cond = 'n'
    # and this will sort '' in the 0 index of the list
    sorted_list()

正确的逻辑应该是:

if bird in bird_list:
    print(bird, 'is already in the list.')
elif bird != '':
    bird_list.append(bird)
    print(bird, 'has been added to the list.')
else:
    cond = 'n'
    sorted_list()

撰写回答