在lis中的所有项前加上相同的字符串

2024-05-23 13:20:04 发布

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

已经做了一些搜索,通过堆栈交换回答了问题,但一直找不到我在寻找什么。

给出以下列表:

a = [1, 2, 3, 4]

我将如何创建:

a = ['hello1', 'hello2', 'hello3', 'hello4']

谢谢!


Tags: 列表堆栈hello1hello2hello4hello3
3条回答

使用list comprehension

['hello{0}'.format(i) for i in a]

列表理解允许您将表达式应用于序列中的每个元素。

演示:

>>> a = [1,2,3,4]
>>> ['hello{0}'.format(i) for i in a]
['hello1', 'hello2', 'hello3', 'hello4']

使用list comprehension

In [1]: a = [1,2,3,4]

In [2]: ["hello" + str(x) for x in a]
Out[2]: ['hello1', 'hello2', 'hello3', 'hello4']

还有一个选项是使用built-in map function

a = range(10)
map(lambda x: 'hello%i' % x, a)

根据WolframH评论编辑:

map('hello{0}'.format, a)

相关问题 更多 >