这个问题与将数字列表转换为附加一些字符串的字符串列表有关。
如何转换以下来源:
source = list (range (1,4))
进入下面的结果:
result = ('a1', 'a2', 'a3')
这个问题与将数字列表转换为附加一些字符串的字符串列表有关。
如何转换以下来源:
source = list (range (1,4))
进入下面的结果:
result = ('a1', 'a2', 'a3')
您可以使用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 x: 'a' + str(x), source)
['a1', 'a2', 'a3']
>>> source = list(range(1,4))
>>> result = ['a{}'.format(x) for x in source]
>>> result
['a1', 'a2', 'a3']
>>> source = list(range(1,4))
>>> ['a%s' % str(number) for number in source]
['a1', 'a2', 'a3']
>>>
你可以这样做:
source = list(range(1,4))
result = []
for i in source:
result.append('a'+str(i))
使用 for 循环将它们附加到 'a'