在格式字符串列表理解? (蟒蛇) [英] List comprehension in format string? (Python)

查看:156
本文介绍了在格式字符串列表理解? (蟒蛇)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表 datalist ,其中 len(datalist)= 4 。假设我希望列表中的每个元素都以这种方式表示为一个字符串:

pre $ 0}'::'{1}'::'{2}''{3}'\\\
.format(datalist [0],datalist [1],datalist [2],datalist [3])

我不喜欢输入 datalist [index]

  s ='{0}'::'{1}'::'{2}'' {3}'\\\
.format(datalist [i] for i in range(4))



<

  Traceback(最近一次调用的最后一个):
文件< stdin> ;,第1行,在< module>
IndexError:元组索引超出范围

有没有人知道实现这种效率的正常运行方式是的,使用 #include -list -list =nofollow noreferrer>参数解包与splat操作符 *

 >>> s ='{0}'::'{1}'::'{2}''{3}'\\\

>>> datalist = ['foo','bar','baz','fizz']
>>> s.format(* datalist)
'foo'::'bar'::'baz''fizz'\\\

>>>

编辑

正如@AChampion所指出的,您也可以在里面使用索引格式字符串本身:

 >>> '{0 [0]}'::'{0 [1]}'::'{0 [2]}''{0 [3]}'\\\
.format(datalist)
'foo'::'bar'::'baz''fizz'\\\


Let's say I have a list datalist, with len(datalist) = 4. Let's say I want each of the elements in the list to be represented in a string in this way:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[0], datalist[1], datalist[2], datalist[3])

I don't like having to type datalist[index] so many times, and feel like there should be a more effective way. I tried:

s = "'{0}'::'{1}'::'{2}' '{3}'\n".format(datalist[i] for i in range(4))

But this doesn't work:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

Does anybody know a functioning way to achieve this efficiency?

解决方案

Yes, use argument unpacking with the "splat" operator *:

>>> s = "'{0}'::'{1}'::'{2}' '{3}'\n"
>>> datalist = ['foo','bar','baz','fizz']
>>> s.format(*datalist)
"'foo'::'bar'::'baz' 'fizz'\n"
>>>

Edit

As pointed out by @AChampion you can also just use indexing inside the format string itself:

>>> "'{0[0]}'::'{0[1]}'::'{0[2]}' '{0[3]}'\n".format(datalist)
"'foo'::'bar'::'baz' 'fizz'\n"

这篇关于在格式字符串列表理解? (蟒蛇)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆