繁体   English   中英

通过打印打印字典

[英]Printing a dictionary with print

为什么

 d = {"A":10,"B":20}
 print(*d, sep=" ")

输出AB而不是10 20

我怎么得到10 20

假设您想要将键和值一起打印,则可以使用生成器表达式:

print(' '.join('{}={}'.format(k,v) for k,v in d.items()))

或者,如果您希望保留sep参数而不是使用str.join

print(*('{}={}'.format(k,v) for k,v in d.items()),sep=' ')

两者都有输出:

A=10 B=20

简单地写

print (*d.values() )

请查看演示的印刷介绍:

>>> def demo(p, *args, **kwargs):
...     print(args)
...     print(kwargs)
...
>>> demo(0, 1, 2, 3, 4, callback='demo_callback')
(1, 2, 3, 4)
{'callback': 'demo_callback'}
  1. *语法需要一个元组/列表;

  2. **语法需要字典; 字典中的每个键值对都将成为关键字参数。

print(* objects,sep ='',end ='\\ n',file = sys.stdout,flush = False)

将对象打印到文本流文件中,以sep分隔,然后以end分隔。 sep,end和file(如果存在)必须作为关键字参数给出。

所有非关键字参数都将像str()一样转换为字符串,并写入流中,以sep分隔,然后以end分隔。 sep和end都必须是字符串; 它们也可以是None,这意味着要使用默认值。 如果没有给出对象,print()只会写完。

file参数必须是带有write(string)方法的对象; 如果不存在或没有,将使用sys.stdout。 由于打印的参数会转换为文本字符串,因此print()不能与二进制模式文件对象一起使用。 对于这些,请改用file.write(...)。

通常是否由文件决定是否对输出进行缓冲,但是如果flush关键字参数为true,则将强制刷新流。

>>> print(d, sep=" ")
{'B': 20, 'A': 10}
>>> print(*d, sep=" ")
B A
>>> print(**d, sep=" ")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'B' is an invalid keyword argument for this function

这是一种有效的方法:

>>> print(*d.values(), sep=" ")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM