Spi*_*uce 1 python string list string-formatting
我之前没有使用str.format(),我想知道如何传入列表值并检索传入这些值的列表输出.
即
listex = range(0, 101, 25)
baseurl = "https://thisisan{0}example.com".format(*listex)
Run Code Online (Sandbox Code Playgroud)
我想要一个列表输出 ["https://thisisan0example.com", "https://thisisan25example.com", "https://thisisan50example.com", etc etc]
但是根据我目前的代码,我只是"https://thisisan0example.com"在跑步时才会这样做print baseurl
您无法使用单一格式显示输出.您可以使用list-comp
>>> 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']
Run Code Online (Sandbox Code Playgroud)
你可以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']
Run Code Online (Sandbox Code Playgroud)
然后可以将其存储在变量baseurl中
baseurl = map("https://thisisan{}example.com".format,listex)
Run Code Online (Sandbox Code Playgroud)
速度比较可以使用 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
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,map这里的速度更快(Python2),因为没有参与lambda