[英]How to remove string quotations, commas and parenthesis from Python itertools output?
[英]How to remove parenthesis from output python
所以我有一個不斷吐出的 function:
(10.3,11.4)
什么時候應該吐出來:
10.3 11.4
我玩了一下,寫了一個簡單的 python 代碼,我似乎理解了這個概念
a=3
b=3
print a,b #returns 3 3
但它不適用於下面的 function,所以我想知道為什么它一直返回 ()
import math
x=10.01
y=9.01
def d():
b = 2.00 * x / math.sqrt(7)
q=round(y-b,2)
r=round(y+b,2)
return q,r
print d() #returns (1.4399999999999999, 16.579999999999998)
print
(正確)打印從d返回的元組。 要單獨打印值,請嘗試以下操作:
print '{} {}'.format(*d())
或這個:
dret = d()
print dret[0],dret[1]
print a,b
不將a,b
解釋為元組,而是作為print
語句的一系列參數。 請注意, print
語句會更改Python3中的語法,以增加混淆。
為了使a,b
情況與q,r
情況平行,它看起來更像是這樣的:
c = a,b
print c
在這種情況下, print
語句將接收元組,而不是兩個單獨的值。
原因在於聲明“return q,r”
您無法從函數返回多個值。 python正在做的是用q和r創建一個元組,並返回它,因為返回q,r被解釋為return(q,r)然后print接受並輸出一個元組。 因此打印(q,r)非常公平
但是,print q,r的執行方式不同,作為多參數打印,並將打印所有參數,其間包含空格。
希望這可以解決任何困惑。
從官方文件;
因此,從像這樣的函數返回多個值,按照定義將它們返回到元組中。
嘗試顯式解包由d()
返回的元組:
In [1]: import math
In [2]: x=10.01
In [3]: y=9.01
In [4]: def d():
...: b = 2.00 * x / math.sqrt(7)
...: q=round(y-b,2)
...: r=round(y+b,2)
...: return q,r
...:
In [5]: a, b = d()
In [6]: print a, b
1.44 16.58
math.sqrt 返回一個具有實部和虛部的復數。 將其更改為 math.sqrt(7).real,復數僅為實數。 這使印刷品如您所願
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.