![](/img/trans.png)
[英]How can I make printing a portion of a dictionary print the mathematical value?
[英]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'}
*
語法需要一個元組/列表;
**
語法需要字典; 字典中的每個鍵值對都將成為關鍵字參數。
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.