Python向Python中的列表元素添加preffix

2024-09-22 14:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]

我有前缀字符串:

/root

是否有任何python方法将前缀字符串添加到列表中的每个元素 因此最终结果如下所示:

lst = ["/root/foo/dir/c-.*.txt","/root/foo/dir2/d-.*.svc","/root/foo/dir3/es-.*.info"]

如果可以在不迭代和创建新列表的情况下完成


Tags: 方法字符串infotxt元素列表fooes
3条回答

已使用:

  1. 列表理解

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

  1. F=字符串

F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value. In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
prefix = '/root'
lst =[ f'{prefix}{path}' for path in lst] 

print(lst)

使用列表理解和字符串连接:

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]
   
print(['/root' + p for p in lst])

# ['/root/foo/dir/c-.*.txt', '/root/foo/dir2/d-.*.svc', '/root/foo/dir3/es-.*.info']

我不确定pythonic,但这也是可能的方式

list(map(lambda x: '/root' + x, lst))

这里是列表comp和mapList comprehension vs map之间的比较

也要感谢@chris rands在没有lambda的情况下学会了更多的方法

list(map('/root'.__add__, lst))

相关问题 更多 >