使用 string.format 进行整数列表连接

eme*_*eth 3 python string list

正如使用 Python 连接具有整数值的列表一样,可以通过转换str然后连接它们来连接整数列表。

顺便说一句,我想foo bar 10 0 1 2 3 4 5 6 7 8 9先获取几个数据的位置(foo, bar),然后是列表的大小10,然后elements是。

string.format用作

x = range(10)
out = '{} {} {} {}'.format('foo', 'bar', len(x), x)
Run Code Online (Sandbox Code Playgroud)

outfoo bar 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

为了解决问题我可以将代码重写为

out = '{} {} {} '.format('foo', 'bar', len(x)) + ' '.join([str(i) for i in x])
Run Code Online (Sandbox Code Playgroud)

它看起来不一致(混合string.formatjoin)。我试过

slot = ' {}' * len(x)
out = ('{} {} {}' + slot).format('foo', 'bar', len(x), *x)
Run Code Online (Sandbox Code Playgroud)

我认为它仍然没有吸引力。有没有办法string.format仅使用连接整数列表?

NPE*_*NPE 5

我可能错过了你的问题的要点,但你可以简单地扩展你链接到的方法,如下所示:

>>> x = range(10)
>>> out = " ".join(map(str, ["foo", "bar", len(x)] + x))
>>> out
'foo bar 10 0 1 2 3 4 5 6 7 8 9'
Run Code Online (Sandbox Code Playgroud)


the*_*eye 5

既然你看重吸引力,只想用一根线,并且format只用,你就可以做到

'{} {} {}{}'.format('foo', 'bar', len(x), ' {}' * len(x)).format(*x)
# foo bar 10 0 1 2 3 4 5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)