2017-10-10 40 views
2

因此,我的老師希望我使用兩個函數製作一個程序,將「名人堂」添加到列表中的每個棒球選手。我們應該開始用這個程序打印每個名單上球員的名字:使用函數將一個字符串添加到列表中的每個項目上

def show_players(players): 
    """Show list of baseball players""" 
    for player in players: 
     print(player.title()) 

baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds'] 
show_players(baseball_players) 

我們必須寫另一個功能,增加了「名人堂成員」到每一個運動員,這是我已經得到了(它不工作,我怎麼想):

def show_players(players): 
    """Show list of baseball players""" 
    for player in players: 
     print(player.title()) 

def make_HOF(baseball_players): 
    """Make each baseball player a Hall of Famer""" 
    HOF = "Hall of Famer " 
    for player in baseball_players: 
     HOF_players = [HOF + player] 
    return HOF_players 

HOF_players = []   
baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds'] 
make_HOF(baseball_players) 
show_players(HOF_players) 
+0

[String Concatenation and Formatting](http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python) – Rafael

回答

0

當你正在做的事情到列表中的每個元素,你應該認爲這是應用的地圖功能在名單上。在這種情況下,您的映射函數將字符串"Hall of Famer "預先添加到列表中的每個字符串。

有兩種方法可以在Python中編寫簡單的地圖。一種是通過使用用於循環

new_xs = [] 
for x in xs: 
    new_xs.append(your_func(x)) 

另一個,等等優選的,是使用一個列表理解

new_xs = [your_func(x) for x in xs] 

括號中第三,以上,實際上是使用內置在map,其具有因爲列表理解非常容易編寫和閱讀,因此不受歡迎。

new_xs = list(map(your_func, xs)) 
# N.B. if you don't need this as an actual list, just something you can iterate over 
# you can leave out the list(...) call. 

在您的例子your_func應該是這樣的:

def add_HOF(s): # mapping function 
    return "Hall of Famer " + s 

這是很容易在網上寫,尤其是作爲一個列表理解

def add_HOFs(players): 
    return ["Hall of Famer " + player.title() for player in players] 
0

當你把HOF_players = [ HOF +播放器],它沒有添加任何東西到你的列表中,並且它添加了字符串和一個沒有達到你所期望的列表。嘗試使用HOF_players.append(HOF + player),以便將字符串'Hall of Famer'添加到字符串baseball_players [players]並將其添加到列表中。

def show_players(players): 
    """Show list of baseball players""" 
    for player in players: 
     print(player.title()) 

baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds'] 
show_players(baseball_players) 

def make_HOF(baseball_players): 
     """Make each baseball player a Hall of Famer""" 
     HOF = "Hall of Famer " 
     for player in baseball_players: 
      HOF_players.append(HOF + player) 
    return HOF_players 

HOF_players = [] 
make_HOF(baseball_players) 
show_players(HOF_players) 

如果問題修復了,謝謝。

0

我想到了我自己!

def show_players(players): 
    """Show list of baseball players""" 
    for player in players: 
     print(player.title()) 

def make_HOF(titless_players): 
    """Make each baseball player a Hall of Famer""" 
    for player in titless_players: 
     player = "Hall of Famer: " + player 
     HOF_players.append(player) 
    return HOF_players 

HOF_players = []   
baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds'] 
make_HOF(baseball_players) 
show_players(HOF_players) 

它輸出: 名人堂成員作者:傑基·羅賓森 名人堂成員作者:貝比·魯斯 名人堂成員作者:邦茲

..這正是我想要它做的事!甜!

相關問題