亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢查列表中最后一個元素中有多少在 python 中是相等的?

如何檢查列表中最后一個元素中有多少在 python 中是相等的?

慕后森 2023-02-12 18:56:23
我將整數一個一個地附加到列表中(使用循環),如下所示:A.append(x)其中 x 是一個整數,最終給出例如:A = [4, 8, 2, 4, 3, 7, 7, 7]在每個循環中,即在將每個整數添加到數組末尾之后,我想檢查是否已將相同的整數添加了一定次數(例如,在下面的示例中為 3 次),如果存在則拋出異常所以。偽代碼:if somewayofcheckingA == 3:     raise Exception("Lots of the latest integers are similar")我可以執行以下操作,但如果我想檢查 100 次重復,那么顯然代碼會變得一團糟。if A[-1] == A[-2] and A[-2] == A[-3]:     raise Exception("Lots of the latest integers are similar")謝謝!
查看完整描述

4 回答

?
30秒到達戰場

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")


查看完整回答
反對 回復 2023-02-12
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

如果您只想檢查最后 3 個,那么就可以了。


limit = 3

if len(set(A[-limit:])) == 1:

    raise Exception("Lots of the latest integers are similar")


查看完整回答
反對 回復 2023-02-12
?
冉冉說

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")

**此代碼檢查列表的任何其他索引中最后一個元素的出現


查看完整回答
反對 回復 2023-02-12
?
MM們

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,但你可能會迷失在其中。


查看完整回答
反對 回復 2023-02-12
  • 4 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號