2016-09-14 100 views
1

我正在尋找最好的方法來獲取一個列表,並生成一個新列表,其中列出的每個項目都與特定字符串連接起來。將Python列表串聯到新列表中的字符串

例須藤代碼

list1 = ['Item1','Item2','Item3','Item4'] 
string = '-example' 
NewList = ['Item1-example','Item2-example','Item3-example','Item4-example'] 

嘗試

NewList = (string.join(list1)) 
#This of course makes one big string 
+0

NewList = [x + list1中x的字符串] –

+0

感謝所有提示響應。儘管所有提出的答案在技術上都是正確的,但我首選@eugene y – iNoob

回答

3

使用字符串連接:

>>> list1 = ['Item1', 'Item2', 'Item3', 'Item4'] 
>>> string = '-example' 
>>> [x + string for x in list1] 
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example'] 
5

如果你想創建一個列表,列表理解通常是我們該做的。在列表理解

new_list = ["{}{}".format(item, string) for item in list1] 
1

concate列表項和字符串

>>>list= ['Item1', 'Item2', 'Item3', 'Item4'] 
>>>newList=[ i+'-example' for i in list] 
>>>newList 
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example'] 
2

另一種列出的理解是使用map()

>>> map(lambda x: x+string,list1) 
['Item1-example', 'Item2-example', 'Item3-example', 'Item4-example'] 

ñ ote,list(map(lambda x: x+string,list1))在Python3中。