Skip to main content
 首页 » 编程设计

Python str.format() --- 传入列表,输出列表

2025年05月04日14kuangbin

我之前没有使用过 str.format(),我想知道如何传入列表值并检索包含这些传入值的列表输出。

即

listex = range(0, 101, 25) 
baseurl = "https://thisisan{0}example.com".format(*listex) 

我想要一个列表输出,如 ["https://thisisan0example.com", "https://thisisan25example.com", "https://thisisan50example.com", etc etc]

但是在我上面的当前代码中,当我运行 print baseurl

时,我只会得到 "https://thisisan0example.com"

请您参考如下方法:

您无法使用单一格式获得如图所示的输出。您可以使用列表组件

>>> listex = range(0, 101, 25) 
>>> ["https://thisisan{}example.com".format(i) for i in listex] 
['https://thisisan0example.com', 'https://thisisan25example.com', 'https://thisisan50example.com', 'https://thisisan75example.com', 'https://thisisan100example.com'] 

您可以使用 map在这里(如果你使用的是 Py3,包装一个 list 调用),

>>> map("https://thisisan{}example.com".format,listex) 
['https://thisisan0example.com', 'https://thisisan25example.com', 'https://thisisan50example.com', 'https://thisisan75example.com', 'https://thisisan100example.com'] 

然后可以将其存储在您的变量 baseurl 中作为

baseurl = map("https://thisisan{}example.com".format,listex) 

速度比较可以使用timeit

$ python -m timeit 'listex = range(0, 101, 25);["https://thisisan{}example.com".format(i) for i in listex]' 
1000000 loops, best of 3: 1.73 usec per loop 
$ python -m timeit 'listex = range(0, 101, 25);map("https://thisisan{}example.com".format,listex)' 
1000000 loops, best of 3: 1.36 usec per loop 

如您所见,map 在这里 (Python2) 更快,因为没有涉及 lambda