使用列表理解在Python中连接字典中的项目

发布于 2024-08-15 18:53:30 字数 125 浏览 5 评论 0原文

编辑:澄清了一点问题

如何

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

再浓的妆也掩不了殇 2024-08-22 18:53:30

没有理由在这里使用列表理解。

Python 3.x:

for k,v in mydict.items():
  print(k, '=', v)

Python 2.x:

for k,v in mydict.iteritems():
  print k, '=', v

编辑,因为另一个答案中OP的评论:

如果您将其传递给函数而不是在此处打印,那么您应该将生成器传递给函数或字典本身,让函数处理它需要做的任何事情。

这比将其转换为甚至不需要的范围内的字符串要好得多。该函数应该执行此操作,因为这就是它的用途。

我制作了一个包装函数,因为编辑主函数是不可能的。

def log_wrap(mydict):
    mystr = '\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()])
    write_to_log(mydict)

log_wrap(mydict)

There's no reason to use list comprehension here.

Python 3.x:

for k,v in mydict.items():
  print(k, '=', v)

Python 2.x:

for k,v in mydict.iteritems():
  print k, '=', v

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.

def log_wrap(mydict):
    mystr = '\n'.join(['%s = %s' % (k,v) for k,v in mydict.iteritems()])
    write_to_log(mydict)

log_wrap(mydict)
瀞厅☆埖开 2024-08-22 18:53:30
print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())
print '\n'.join('%s = %s' % (key, value) for key, value in d.iteritems())
萌逼全场 2024-08-22 18:53:30

显式优于隐式

列表理解是一种创建的方式列表,不是为了避免循环。
来自 PEP 202:

列表推导式提供了更多
创建列表的简洁方法
map() 和 filter() 的情况
和/或嵌套循环目前是
使用过。

所以你应该问自己:
什么时候用 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:

List comprehensions provide a more
concise way to create lists in
situations where map() and filter()
and/or nested loops would currently be
used.

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.

独守阴晴ぅ圆缺 2024-08-22 18:53:30

像这样:

DATA = {'key1': 'value1', 'key2': 'value2'}
print "\n".join(sorted(["%s = %s" % (k,v) for (k,v) in DATA.iteritems()]))

Like this:

DATA = {'key1': 'value1', 'key2': 'value2'}
print "\n".join(sorted(["%s = %s" % (k,v) for (k,v) in DATA.iteritems()]))
死开点丶别碍眼 2024-08-22 18:53:30

我更喜欢 pythonic 方式:

mydict = {'a':1, 'b':2, 'c':3}
for (key, value) in mydict.items():
    print key, '=', value

I prefer the pythonic way:

mydict = {'a':1, 'b':2, 'c':3}
for (key, value) in mydict.items():
    print key, '=', value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文