20

已通过 Stack Exchange 进行了一些搜索,回答了问题,但无法找到我要查找的内容。

给定以下列表:

a = [1, 2, 3, 4]

我将如何创建:

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

谢谢!

4

4 回答 4

44

使用列表理解

[f'hello{i}' for i in a]

列表推导式允许您将表达式应用于序列中的每个元素。这里的表达式是一个格式化的字符串文字,并入以 .i开头的字符串hello

演示:

>>> a = [1,2,3,4]
>>> [f'hello{i}' for i in a]
['hello1', 'hello2', 'hello3', 'hello4']
于 2012-11-11T13:14:44.317 回答
11

另一种选择是使用内置的地图功能

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

根据 WolframH 评论编辑:

map('hello{0}'.format, a)
于 2012-11-11T13:20:15.247 回答
1

使用列表理解

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

In [2]: ["hello" + str(x) for x in a]
Out[2]: ['hello1', 'hello2', 'hello3', 'hello4']
于 2012-11-11T13:14:40.307 回答
0

你也可以使用%而不是format()

>>> a = [1, 2, 3, 4]
>>> ['hello%s' % i for i in a]
['hello1', 'hello2', 'hello3', 'hello4']
于 2018-05-07T09:48:07.753 回答