4 回答

TA貢獻1828條經驗 獲得超6個贊
將列表傳遞給set()將返回一個包含列表中所有唯一值的集合。n您可以使用切片表示法使用以下命令獲取最后一個值的列表
n = 3
if len(A) >= n and len(set(A[-n:])) == 1:
raise Exception("Lots of the latest integers are similar")

TA貢獻1796條經驗 獲得超7個贊
如果您只想檢查最后 3 個,那么就可以了。
limit = 3
if len(set(A[-limit:])) == 1:
raise Exception("Lots of the latest integers are similar")

TA貢獻1877條經驗 獲得超1個贊
您可以使用 collections.Counter() 來計算最后一個元素出現的次數。例如:
occurrences = collections.Counter(A)
if occurrences[A[-1]] >= 3:
raise Exception("Lots of the latest integers are similar")
或者更簡單的方法
if A.count(A[-1]) >= 3:
raise Exception("Lots of the latest integers are similar")
**此代碼檢查列表的任何其他索引中最后一個元素的出現

TA貢獻1886條經驗 獲得超2個贊
lists = [1,4,3,3];
def somewayofcheckingA(lists, a):
lists.reverse()
i = 0
k = lists[0]
count = 0
while i < a:
if(lists[i] == k):
count= count+1
i = i+1
return count
print(test(lists, 3))
其中 lists 是列表,a 是您要檢查的次數
這個答案很容易理解并利用了基本的循環和條件語句,我認為你應該在嘗試其他建議的解決方案之前掌握這些內容,這些解決方案更像 pythonic,但你可能會迷失在其中。
添加回答
舉報