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