0

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

如何转换以下来源:

source = list (range (1,4))

进入下面的结果:

result = ('a1', 'a2', 'a3')
4

4 回答 4

7

您可以使用List Comprehension

# 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

>>> map(lambda x: 'a' + str(x), source)
['a1', 'a2', 'a3']
于 2013-07-24T09:04:48.117 回答
3
>>> source = list(range(1,4))
>>> result = ['a{}'.format(x) for x in source]
>>> result
['a1', 'a2', 'a3']
于 2013-07-24T09:04:41.867 回答
2
>>> source = list(range(1,4))
>>> ['a%s' % str(number) for number in source]
['a1', 'a2', 'a3']
>>>
于 2013-07-24T09:05:32.790 回答
0

你可以这样做:

source = list(range(1,4))
result = []
for i in source:
    result.append('a'+str(i))

使用 for 循环将它们附加到 'a'

于 2013-07-24T09:06:53.547 回答