2014-10-20 48 views
1

我需要幫助,爲我的任務額外增加一部分功能。目標是製作一個列表,然後允許用戶輸入他們自己的數據(在這種情況下是鳥類),然後將其排序並返回鳥類。額外的信貸部分是允許用戶在之後編輯任何信息。我不知道如何查找/替換用戶提供的內容。使用用戶輸入查找並替換列表(python)

代碼:

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') 
+0

那麼我的嘗試是它所說的編輯下面的一切。但是會發生什麼呢,比如說我輸入了烏鴉,這個烏鴉會在列表中出現0,我得到'列表中沒有找到條目' – 2014-10-20 01:49:54

回答

1

首先,您可以使用.index在列表中查找某個項目的位置。

但在你的代碼,它是當你進入這將是在列表索引0的名稱你得到了'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() 
+0

非常感謝@LarryLee!我們還沒有了解elif語句,或者!=這使得代碼看起來好多了。我也沒有得到「已被添加到列表中。」當我按回車完成。這是一個很大的幫助。 我仍然遇到的問題是讓它使用索引來查找用戶生成的輸入。所以我能夠使用索引時,我只是在尋找名單[0],但現在我希望它成爲他們的任何東西。到目前爲止,我所嘗試過的所有東西都只是給我返回「列表中未找到條目」 – 2014-10-20 20:13:51

1

看起來你打算找給他們的名字一個任意鳥的位置解決了編輯的問題。要在python列表中查找具有特定值的項目,請使用list.indexstdtypes documentation