Python 为 python 中的列表元素添加前缀

Python adding preffix to list elements in python

我有字符串列表

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

我有前缀字符串:

/root

有没有pythonic的方法可以将前缀字符串添加到列表中的每个元素 所以最终结果将如下所示:

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

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

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

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))

这里有list comp和map的比较List comprehension vs map

还要感谢@chris-rands 学习了另一种不用 lambda 的方法

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

已用:

  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"]
prefix="/root"

res = [prefix + x for x in lst]
print(res)

一个简单的列表理解-

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

print([prefix + string for string in lst]) # You can give it a variable if you want