简体   繁体   English

将单个字符串连接到列表中包含的许多其他元素的最干净的方法

[英]cleanest way to concatenate a single string to many other element contained in a list

What I have:我拥有的:

string = "string"
range_list = list(range(10))

What I want:我想要的是:

['string0',
 'string1',
 'string2',
 'string3',
 'string4',
 'string5',
 'string6',
 'string7',
 'string8',
 'string9']

What I usually do:我通常做的事情:

import pandas as pd
(string+pd.Series(range_list).astype(str)).tolist()

What I would like to do:我想做什么:
obtain the same expected output from the same input, without importing libraries nor using loops从相同的输入获得相同的预期 output,无需导入库或使用循环

Since there is probably no way to do this complying my requests, any other solution cleaner and/or more performing than mine is well accepted.由于可能无法按照我的要求执行此操作,因此可以接受任何其他比我的更清洁和/或性能更好的解决方案。 Thanks in advice.感谢您的建议。

You can do this using list comprehension and f-string.您可以使用列表理解和 f-string 来做到这一点。

[f"{string}{idx}" for idx in range_list]

You can use map with a function or a lambda to avoid using a loop.您可以将map与 function 或 lambda 一起使用,以避免使用循环。

def get_string(x):
    return f'string{x}'

list(map(get_string, range(10)))

or with a lambda:或使用 lambda:

list(map(lambda x: f'string{x}', range(10)))

For your case, you could write:对于你的情况,你可以写:

list(map(lambda x: f'{string}{x}', range_list))

Since, you want solutions without loops:因为,你想要没有循环的解决方案:

string = "string"
range_list = list(range(10))

list(map(lambda x: string + x, np.array(range_list).astype(str)))

Or或者

list(map(lambda x: 'string{}'.format(x), range_list))

This works too这也行

string = "string"

str_list = [string + str(i) for i in range(10)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM