将字符串连接到数字列表,每次重复字符串(Python)

huangapple go评论72阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月29日 07:40:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76577293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定