我很好奇,如果這樣的事情是可能的中間:條件表達式中的
print "lajsdflk"+ (if x>1:"123123";else:"0000000") +"[email protected]#"
未進行具體打印但只是數字的任意功能;另一個例子:
print 596* (if statementX: 6545; else: 9874) /63
如果可能我想保持一行。
我很好奇,如果這樣的事情是可能的中間:條件表達式中的
print "lajsdflk"+ (if x>1:"123123";else:"0000000") +"[email protected]#"
未進行具體打印但只是數字的任意功能;另一個例子:
print 596* (if statementX: 6545; else: 9874) /63
如果可能我想保持一行。
您可以使用conditional expression,這樣
>>> "lajsdflk" + ("123123" if 5 > 1 else "0000000") + "[email protected]#"
'[email protected]#'
>>> "lajsdflk" + ("123123" if 0 > 1 else "0000000") + "[email protected]#"
'[email protected]#'
因爲Python接受在if
的表達任何Truthy值,你甚至可以使用任何功能,這樣
>>> "lajsdflk" + ("123123" if "abcd1234".isalnum() else "0000000") + "[email protected]#"
'[email protected]#'
還有另一個人使用的技巧。它是這樣的
>>> "lajsdflk" + ("0000000", "123123")[5 > 1] + "[email protected]#"
'[email protected]#'
>>> "lajsdflk" + ("0000000", "123123")[0 > 1] + "[email protected]#"
'[email protected]#'
在這裏,一個元組準備好可能的結果,並根據比較操作的結果,選擇可能的值。在這裏,5 > 1
進行評估,發現是Truthy既然Python的True
等於1,False
等於0
,5 > 1
評估爲1
>>> 0 == False
True
>>> 1 == True
True
注:這招有問題。考慮這種情況下,
>>> 1 + (2, 3/0)[4 > 0] + 5
Traceback (most recent call last):
File "<input>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
因爲,在創建的元組時,所有的值進行評估和Python不能0
劃分1
。但是,這個問題不會出現在條件表達式中,
>>> 1 + (2 if 4 > 0 else 3/0) + 5
8
因爲它只有在分支命中時才計算值。
我欣賞額外的細節!我想我現在明白了,謝謝! – Kweb123 2015-03-13 07:07:55
我添加了excel標籤,因爲它看起來像你的問題更多地是關於excel而不是關於Python。 – orlp 2015-03-13 07:02:34
語法如下:'print 596 *(6545 if True else 9874)/ 63' – perreal 2015-03-13 07:02:41