2015-05-11 38 views
0

我想知道你的首選方法來初始化布爾值。我自己找不到任何解決方案的好理由。Pythonic方式初始化布爾值

初始化後我在循環中使用isLastInMonth並且不想隨時調用monthrange!

實施例1:

if monthrange(2015, 5)[1] == today.day: 
    isLastInMonth = True 
else: 
    isLastInMonth = False 

實施例2:

isLastInMonth = False 
if monthrange(2015, 5)[1] == today.day: 
    isLastInMonth = True 

編輯:

好像你喜歡的第三個:

實施例3:

isLastInMonth = monthrange(2015, 5)[1] == today.day 

一些答案參考我老例如:

實施例1:

if fooA == True: 
    fooB = True 
else: 
    fooB = False 

實施例2:

fooB = False 
if fooA == True: 
    fooB = True 
+1

爲什麼不直接分配'fooB = fooA '? –

+0

'fooA = fooB' - 'fooB'怎麼樣也是布爾值? – sebastian

+2

在擔心Pythonic初始化'fooB'的方式之前,也許你應該查看Pythonic的方式來測試'fooA'(提示:那不是它)? – jonrsharpe

回答

3

給定條件(fooA),初始化fooB:

>>> fooB = fooA 

和補充:

>>> fooB = not fooA 

所以,你的例子:

>>> from datetime import date 
>>> from calendar import monthrange 
>>> 
>>> 
>>> isLastInMonth = monthrange(2015,5)[1] == date.today() 

我不會硬編碼2015年或5,但我想這只是一個例子。

+0

爲什麼補充? –

+0

他的兩個例子。初始化爲「與條件相同的值」和「補充條件」 – folkol

+0

啊,我誤讀了第二個例子。無論如何,我會留下我的第二個例子,以避免OP使用if語句。 – folkol

2

你舉的例子是等價於:

fooB = fooA 
2

我喜歡fooB = fooA

In [16]: fooA = True 

In [17]: fooB = fooA 

In [18]: fooB 
Out[18]: True 

In [19]: fooA = False 

In [20]: fooB 
Out[20]: True 

匹配編輯:

isLastInMonth = monthrange(2015, 5)[1] == today.day 
+0

我在循環中使用isLastInMonth並且不想隨時調用monthrange。 –

+1

在循環中使用isLastInMonth不會導致再次調用月份範圍。 'isLastInMonth = monthrange(2015,5)[1] == today.day'將調用monthrange一次,獲取索引1處的元素,並將其與today.day進行比較,然後將範圍內的isLastMonth設置爲True或False。 – DTing