使用列表理解在Python中连接字典中的项目
编辑:澄清了一点问题
如何
key1 = value1
key2 = value2
以相对快速的方式从具有该格式的字典中获取字符串? (相对于普通串联)
EDIT: Clarified the question a bit
How can I get a string from a dictionary with the format
key1 = value1
key2 = value2
in a relatively fast way ? (relative to plain concatenation)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
没有理由在这里使用列表理解。
Python 3.x:
Python 2.x:
编辑,因为另一个答案中OP的评论:
如果您将其传递给函数而不是在此处打印,那么您应该将生成器传递给函数或字典本身,让函数处理它需要做的任何事情。
这比将其转换为甚至不需要的范围内的字符串要好得多。该函数应该执行此操作,因为这就是它的用途。
我制作了一个包装函数,因为编辑主函数是不可能的。
There's no reason to use list comprehension here.
Python 3.x:
Python 2.x:
EDIT because of comment by OP in another answer:
If you're passing it to a function and not printing it here, then you should just pass the generator to the function, or the dict itself and let the function handle whatever it needs to do with it.
This is much better than converting it to a string inside a scope where it's not even needed. The function should do that, since that's where it's used.
I made a wrapper function, since editing the main function is out of the question.
显式优于隐式
列表理解是一种创建的方式列表,不是为了避免循环。
来自 PEP 202:
所以你应该问自己:
什么时候用 Python 创建此代码有用?它可能更紧凑,但代码读取的次数比编写的次数多,那么它的优势是什么?
Tor Valamo 的解决方案虽然不是原始请求中所要求的,但在我看来更具可读性,因此应该是首选。
问题更新后编辑
str.join
是从列表中实现快速串联的好方法 - Nadia 和 Ritchie 的回复是如何使用它的好例子。再说一遍,我不会在一行中执行所有操作,但我会将其拆分为多个步骤以强调可读性。
Explicit is better than implicit
List comprehension is a way to create list, not to avoid loops.
From PEP 202:
So you should ask yourself:
When is it useful to create this code in Python? It may be more compact but code is read many more times than it is written so what is the advantage in it?
Tor Valamo's solution, although not what was asked for in the original request, is in my opinion far more readable, and therefore should be preferred.
EDIT after question update
str.join
is a good way to implement a fast concatenation from a list - and replies from Nadia and Ritchie are good examples of how to use it.Again, I would not perform everything in a single line, but I would split it in various steps to emphasize readability.
像这样:
Like this:
我更喜欢 pythonic 方式:
I prefer the pythonic way: