2016-11-10 65 views
-2

我試圖使用具有1個預定義函數和1個參數的map函數。一切工作正常,直到我調用地圖函數的list()。最後它顯示使用map時的列表索引超出範圍()

IndexError: list index out of range

但是,當我只是在不使用map()的情況下調用列表上的函數時,它是可以的。任何人都可以嘗試並幫助我識別錯誤嗎?


people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] 

def split_title_and_name(person): 

    name_list=[] 

    for i in person: 
     i = i.split()[0]+" "+i.split()[-1] 
     name_list.append(i) 

    return name_list 

split_title_and_name(people) 
list(map(split_title_and_name, people)) 
+0

你可以修復你的縮進。 'map'接收每個人並應用函數'split_title_and_name()'。 'split_title_and_name('Chistopher Brooks博士')與發送名單清單非常不同。 – AChampion

+0

你的功能似乎是專門爲可直接使用名稱*而設計的。當然,如果你把它映射到'people',那麼它會拋出一個錯誤,因爲當你爲'我親自迭代'時,它遍歷*單個名字*的單個*字符*。當'i'到達空間時,'split'返回並且空列表'[]'並且索引到一個空列表將拋出'IndexError' –

回答

0

你的功能split_title_and_name作品的人的名單,當你希望它在一個時間一個人工作:

def split_title_and_name(person): 
    return person.split()[0] + " " + person.split()[-1] 
1

這些都不是相同的功能。你的功能運行在一個人的列表上。 適用於各個元件。因此,你打電話

split_title_and_name('Dr. Christopher Brooks') 
split_title_and_name('Dr. Kevyn Collins-Thompson') 
... 

看到問題了嗎?

0

這裏是一個更好的解決方案:

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] 

def split_title_and_name(person): 
    title = person.split()[0] 
    lastname = person.split()[-1] 
    return '{} {}'.format(title, lastname) 

list(map(split_title_and_name, people)) 

看起來,當我用格式化功能不太複雜。