![](/img/trans.png)
[英]Python Pandas check if a value occurs more then once in the same day
[英]Python: check if last value of list occurs more than once
問題:
編寫一個程序,搜索列表以查看列表中的最后一個值是否出現多次。 如果最后一個值出現多次,則返回true。 否則,返回false。 如果列表為空,則返回false。
我的代碼:
def go(list1):
for i in range(0,len(list1)):
if list1[i] is list1[-1:]:
return True
else:
return False
print ( go( [-99,1,2,3,4,5,6,7,8,9,10,5] ) )
print ( go( [10,9,8,7,6,5,4,3,2,1,9] ) )
print ( go( [10,20,30,40,50,-11818,40,30,20,10] ) )
print ( go( [32767] ) )
print ( go( [7,7,7,7] ) )
print ( go( [9,10,-88,100,-555,1000] ) )
print ( go( [10,10,10,11,456,10,10] ) )
print ( go( [-111,1,2,3,9,11,20,30] ) )
print ( go( [9,8,7,6,5,4,3,2,0,-2,9,9] ) )
print ( go( [12,15,18,21,23,1000] ) )
print ( go( [250,19,17,15,13,11,10,9,6,3,2,1,250] ) )
print ( go( [] ) )
我的輸出:
False
False
False
False
False
False
False
False
False
False
False
False
期望的輸出:
True
True
True
False
True
False
True
False
True
False
True
False
我究竟做錯了什么? 為什么我的所有輸出都變為假?
你不應該使用is
在這里,因為is
不檢查值的平等,而是為引用的平等。
相反,您可以arr[-1] in arr[:-1]
使用arr[-1] in arr[:-1]
來查看列表的最終值是否存在於列表中的任何其他位置。
x = [-99,1,2,3,4,5,6,7,8,9,10,5]
def is_last_contained(arr):
return arr[-1] in arr[:-1]
print(is_last_contained(x))
輸出:
True
您編寫的代碼中有幾個錯誤:
range(0,len(list1))
應該是range(0,len(list1)-1)
因為你不想將最后一個元素與它自己進行比較。 list1[-1:]
應該是list1[-1]
。 前者選擇切片,后者選擇單個元素。 話雖如此,@ chrisz的解決方案更加Pythonic和簡潔:)
你的錯誤是你試圖將一個元素與一個列表進行比較。 另一個錯誤是,你正在使用的關鍵字is
不是==
。 為了檢查列表中是否存在多個最后一個元素,您需要檢查當前元素是否與最后一個元素相等且它們的索引是否不同(這意味着有多個具有相同值的元素)。 我的推薦如下:
def go(list1):
length = len(list1)
for i in range(0,length):
if list1[i]==list1[-1] and not i==length-1:
return True
else:
return False
print ( go( [-99,1,2,3,4,5,6,7,8,9,10,5] ) )
print ( go( [10,9,8,7,6,5,4,3,2,1,9] ) )
print ( go( [10,20,30,40,50,-11818,40,30,20,10] ) )
print ( go( [32767] ) )
print ( go( [7,7,7,7] ) )
print ( go( [9,10,-88,100,-555,1000] ) )
print ( go( [10,10,10,11,456,10,10] ) )
print ( go( [-111,1,2,3,9,11,20,30] ) )
print ( go( [9,8,7,6,5,4,3,2,0,-2,9,9] ) )
print ( go( [12,15,18,21,23,1000] ) )
print ( go( [250,19,17,15,13,11,10,9,6,3,2,1,250] ) )
print ( go( [] ) )
輸出:
True
True
True
False
True
False
True
False
True
False
True
False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.