用字符串将Python列表串联成新的lis

2024-07-08 08:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找最好的方法来获取一个stirng列表,生成一个新的列表,从上一个列表中的每一项连接一个特定的字符串。你知道吗

sudo代码示例

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

Tags: 方法字符串代码示例列表stringexamplesudo
3条回答

在列表中使用字符串串联:

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

如果你想创建一个列表,列表理解通常是要做的事情。你知道吗

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

列表理解的另一种方法是使用map()

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

注意,list(map(lambda x: x+string,list1))在Python3中。你知道吗

相关问题 更多 >

    热门问题