![](/img/trans.png)
[英]The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() using panda python
[英]Ambiguous behavior of using “not” and “bool” together on an empty list in Python
在這個使用Python列表的Stack的簡單實現中。 我有一個小的方法來檢查堆棧是否為空(列表為空)。 我正在使用此方法作為pop方法的檢查條件。 嘗試彈出空堆棧時,pop方法應引發異常。 由於某些原因,這似乎不起作用。 我在這里想念什么嗎? 請幫忙!
__author__ = '@arun'
# Stack simple implementation using Python list
class Stack(object):
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def is_empty(self):
return not bool(self.items)
def pop(self):
print self.is_empty()
if self.is_empty: # if not stack is empty
return self.items.pop()
else:
raise Exception("Stack Empty!")
def peek(self):
return self.items[-1]
def get_size(self):
return len(self.items)
if __name__ == '__main__':
stack = Stack()
print stack.get_size()
stack.push(23)
stack.push(3)
print stack.get_size()
print stack.pop()
print stack.pop()
print stack.get_size()
#print stack.pop()
輸出:
0
2
False
3
False
23
0
當is_empty()返回False時,為什么pop()方法會彈出元素?
if self.is_empty:
它將始終評估為True
,因為這是真值 。 您需要像這樣調用函數
if self.is_empty():
一個建議:您可能只想在is_empty()
為False
時才pop
值,像這樣
if not self.is_empty():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.