首页 > 解决方案 > python - 如何检查列表中的最后一个元素中有多少在python中是相等的?

问题描述

我将整数一一附加到列表中(使用循环),如下所示:

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

谢谢!

标签: pythonlist

解决方案


将列表传递给set()将返回一个包含列表中所有唯一值的集合。您可以使用切片表示法获取最后一个n值的列表,方法如下

n = 3
if len(A) >= n and len(set(A[-n:])) == 1:
    raise Exception("Lots of the latest integers are similar")

推荐阅读