将数字列表转换为附加某些字符串的字符串列表

2021-10-17 13:25:46 发布

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

这个问题与将数字列表转换为附加一些字符串的字符串列表有关。你知道吗

如何转换以下源:

source = list (range (1,4))

结果如下:

result = ('a1', 'a2', 'a3')
3条回答
网友
1楼 ·
>>> source = list(range(1,4))
>>> ['a%s' % str(number) for number in source]
['a1', 'a2', 'a3']
>>>
网友
2楼 ·

您可以使用列表理解:

# In Python 2, range() returns a `list`. So, you don't need to wrap it in list()
# In Python 3, however, range() returns an iterator. You would need to wrap 
# it in `list()`. You can choose accordingly. I infer Python 3 from your code.

>>> source = list(range(1, 4))
>>> result = ['a' + str(v) for v in source]
>>> result
['a1', 'a2', 'a3']

^{}^{}

>>> map(lambda x: 'a' + str(x), source)
['a1', 'a2', 'a3']
网友
3楼 ·
>>> source = list(range(1,4))
>>> result = ['a{}'.format(x) for x in source]
>>> result
['a1', 'a2', 'a3']

相关问题