已经做了一些搜索Stack Exchange回答的问题,但一直无法找到我要找的东西.
鉴于以下列表:
a = [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
我将如何创建:
a = ['hello1', 'hello2', 'hello3', 'hello4']
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mar*_*ers 38
使用列表理解:
['hello{0}'.format(i) for i in a]
Run Code Online (Sandbox Code Playgroud)
列表推导允许您将表达式应用于序列中的每个元素.
演示:
>>> a = [1,2,3,4]
>>> ['hello{0}'.format(i) for i in a]
['hello1', 'hello2', 'hello3', 'hello4']
Run Code Online (Sandbox Code Playgroud)
Art*_*nka 10
还有一个选择是使用内置的map功能:
a = range(10)
map(lambda x: 'hello%i' % x, a)
Run Code Online (Sandbox Code Playgroud)
根据WolframH编辑评论:
map('hello{0}'.format, a)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14574 次 |
| 最近记录: |