2015-09-20 132 views
-1

我對Python很陌生,所以也許我偶然發現了答案並沒有意識到這一點,但是我整天都在搜索和試驗代碼,並且仍然難以理解以下內容:Python中的組合元素

鑑於以下兩個列表:

List1 = [1, 2, 3] 
List2 = ['a', 'b', 'c'] 

你會如何創建項目list3?

List3 = ['1a', '2b', '3c'] 

回答

0
['{}{}'.format(a,b) for a,b in zip(list1, list2)] 
1

您是否聽說過zip

[str(i)+j for i,j in zip(list1,list2)] 

實施例:

>>> List1 = [1, 2, 3] 
>>> List2 = ['a', 'b', 'c'] 
>>> [str(i)+j for i,j in zip(List1,List2)] 
['1a', '2b', '3c'] 
2

這是一個很好的用例zip()

>>> l1 = [1, 2, 3] 
>>> l2 = ['a', 'b', 'c'] 
>>> 
>>> ['%d%s' % item for item in zip(l1, l2)] 
['1a', '2b', '3c']