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

时间:2015-06-15 16:55:20

标签: python string list string-formatting

之前我没有使用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]

这样的列表输出

但是根据我上面的当前代码,当我运行"https://thisisan0example.com"

时,我只获得print baseurl

3 个答案:

答案 0 :(得分:5)

您无法使用单一格式显示输出。您可以使用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']

您可以在此处使用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的参与

答案 1 :(得分:2)

您可以列出以下内容:

baseurl = ["https://thisisan{0}example.com".format(x) for x in listex]

这实际上循环遍历listex并使用每个元素的给定字符串的唯一版本构建baseurl

答案 2 :(得分:2)

方法-1:使用map和lambda:

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

此处,map()会将lambda函数应用于listex的每个元素,并返回包含lambda函数更改的元素的列表。

方法-2:使用列表理解:

baseurl = ["https://thisisan{0}example.com".format(item) for item in listex]
['https://thisisan0example.com',
 'https://thisisan25example.com',
 'https://thisisan50example.com',
 'https://thisisan75example.com',
 'https://thisisan100example.com']

在这里,我们使用list comprehension来实现所需的结果。