2016-09-14 157 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中。

相关问题