英文:
Concatenate string to list of numbers repeating the string each time (Python)
问题
我有一个数字列表,```[0,1,2,3,4,5,6,7,8,9]```,我想在每个数字前面加上单词```foo```,以得到每次一个字符串:
['foo0','foo1','foo2','foo3','foo4',
'foo5','foo6','foo7','foo8','foo9']
类似于 R 语言中的```paste0('foo',0:9)```函数。
英文:
I have a list of numbers, [0,1,2,3,4,5,6,7,8,9]
and I would like to attach the word foo
in front of each number to get a string each time to get
['foo0','foo1','foo2','foo3','foo4',
'foo5','foo6','foo7','foo8','foo9']
a function like paste0('foo',0:9)
in R.
答案1
得分: 2
Using list comprehension (credit: Barmar):
[ 'foo' + str(i) for i in range(9)]
Using map:
list(map(lambda i: 'foo' + str(i), range(9)))
Using f-strings:
[f'foo{i}' for i in range(9)]
英文:
Using list comprehension (credit: Barmar):
['foo' + str(i) for i in range(9)]
Using map:
list(map(lambda i: 'foo' + str(i), range(9)))
Using f-strings:
[f'foo{i}' for i in range(9)]
答案2
得分: 1
你可以使用 for循环 与 enumerate 内置函数。
strings = [0,1,2,3,4,5,6,7,8,9]
for index, value in enumerate(strings):
strings[index] = "foo" + str(value)
输出
['foo0', 'foo1', 'foo2', 'foo3', 'foo4', 'foo5', 'foo6', 'foo7', 'foo8', 'foo9']
英文:
You can use a for-loop with the enumerate built-in function.
strings = [0,1,2,3,4,5,6,7,8,9]
for index, value in enumerate(strings):
strings[index] = "foo" + str(value)
Output
['foo0', 'foo1', 'foo2', 'foo3', 'foo4', 'foo5', 'foo6', 'foo7', 'foo8', 'foo9']
答案3
得分: 1
你可以使用map和format来构建结果列表:
N = [0,1,2,3,4,5,6,7,8,9]
*foos, = map("foo{}".format,N)
print(foos)
['foo0','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9']
如果你想在原始列表中进行“in-place”操作,你可以将映射赋值给一个下标:
N[:] = map("foo{}".format,N)
英文:
You could use map and format to build the resulting list :
N = [0,1,2,3,4,5,6,7,8,9]
*foos, = map("foo{}".format,N)
print(foos)
['foo0','foo1','foo2','foo3','foo4','foo5','foo6','foo7','foo8','foo9']
If you want to do it "in-place" in the original list, you can assign the mapping to a subscript:
N[:] = map("foo{}".format,N)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论