2014-05-12 63 views
0

我想合併一個列表與另一個長度相同的列表。我的第一個列表包含電影+演員名字的名字。另一個列表包含基於電影的評分。如何將列表合併在一起?

'The Godfather (1972), Marlon Brando, Al Pacino, James Caan'\n", 
'The Godfather: Part II (1974), Al Pacino, Robert De Niro, Robert Duvall',\n", 
'The Dark Knight (2008), Christian Bale, Heath Ledger, Aaron Eckhart',\n", 
'Pulp Fiction (1994), John Travolta, Uma Thurman, Samuel L. Jackson',\n", 

例如,從列表與評級:從名稱+演員名單

例如

'9.0',
'8.9',
'8.9',
'8.9' ,

我想將這兩個列表合併成一個大列表

Names, actors, ratings.

結果應該是這樣的:

'The Godfather (1972), Marlon Brando, Al Pacino, James Caan, 9.0'\n", 
'The Godfather: Part II (1974), Al Pacino, Robert De Niro, Robert Duvall, 8.9',\n", 
'The Dark Knight (2008), Christian Bale, Heath Ledger, Aaron Eckhart, 8.9',\n", 
'Pulp Fiction (1994), John Travolta, Uma Thurman, Samuel L. Jackson, 8.9',\n", 

嘗試這樣做,到目前爲止,但它並沒有幫助我很多。

from pprint import pprint 

Name_Actor_List = [] 
Final_List = [] 



for i in lines: 
    Name_Actor_List.append(i) 

Final_List = Machine_List + ratings  
+0

可能重複的[在Python中合併兩個列表?](http://stackoverflow.com/questions/1720421/merge-two-lists-in-python) – thefourtheye

+0

@thefourtheye - 這不是你的重複鏈接。鏈接的問題是關於將列表附加到另一個列表。這個問題是關於將一​​個列表中的每個元素與另一個列表中的相應元素進行組合。 – Rynant

+0

如果列表元素中的換行符來自'file.readlines()',那麼使用'file.read()。splitlines()'讀取文件會更好。這樣字符串不會包含換行符,並且組合字符串會更容易。 – Rynant

回答

1

相同指數從兩個列表中的項目相結合的最簡單的方法是zip

Final_List = [] 
for name_actor, rating in zip(lines, ratings): 
    Final_List.append(",".join(name_actor, rating)) 
0

像這樣的事情也應該工作:

result = [] 
for index in len(actor_list): 
    result.add('%s,%s', actor_list[index], ratings[index]) 
0

此行應該做的伎倆通過使用map()和一個簡單的lambda函數:

result = map(lambda i: actor_list[i] + ratings[i], range(len(actor_list)))