2017-02-28 63 views
0

我正在編寫一個程序,其中包含一個包含四位美國總統姓名的列表。使用任何你想要的總統。然後,運行一個循環,將四位總統添加到列表中。以列表作爲唯一參數調用另一個函數。這第二個函數應該對列表進行排序,然後循環遍歷列表,以便按照自己的路線打印每個總統的姓名。我有一些代碼完成,但它只打印第一組名稱的列表。我無法弄清楚如何獲得名稱排序並打印列表中輸入的所有名字。打印具有唯一參數的函數的名稱列表

這是我的代碼:

president = 4 

def main(): 

    names = [0] * president 

    for pres in range(president): 
     print('Enter the name of a president',sep='',end='') 
     names[pres] = input() 
     names.sort() 
     print(names) 


    for pres in range(president): 
     print('Enter the name of another president',sep='',end='') 
     names[pres] = input() 


def names(name_list): 
    name_list.sort() 
    return name_list 

回答

0

變量「PRES」獲取在第17行中的第二循環復位(將循環遍歷索引0-3和覆蓋以前的4名總統)。速戰速決也許嘗試都names[pres + 4] = input()在17行和names = [""] * 8第6行

0
for pres in range(president): 
    print('Enter the name of a president',sep='',end='') 
    names[pres] = input() 
    names.sort() 
    print(names) 

你不需要每次添加一個新的總統將它的時間做names.sort()。如果你想添加4個總統,然後添加它。排序是最後一步,對吧?

在你的第二個循環中,你使用相同的索引來添加另一個總統。這將改變你的名單中的元素,你將仍然有4位總統,沒有更多。我的建議是使用

new_president = input() 
names.append(new_president) 

,而不是

names[pres] = input() 

這裏是我完整的代碼:

def create_presidents(no_presidents=4): 
    presidents = [] 
    for _ in range(no_presidents): 
     presidents.append(input("Enter a name: ")) 
    # More presidents 
    for _ in range(no_presidents): 
     presidents.append(input("Enter another name: ")) 
    presidents.sort() 
    return presidents 

def print_presidents(presidents): 
    for president in presidents: 
     print(president) 

if __name__ == "__main__": 
    no_presidents = 4 
    presidents = create_presidents(no_presidents) 
    print_presidents(presidents) 
0

IM甚至比我現在開始更加迷茫:(伊武,我認爲4個總統名字默認應該在列表中,然後用戶輸入並添加4個其他名字,然後它應該顯示該列表。