python - 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")
谢谢!
解决方案
将列表传递给set()
将返回一个包含列表中所有唯一值的集合。您可以使用切片表示法获取最后一个n
值的列表,方法如下
n = 3
if len(A) >= n and len(set(A[-n:])) == 1:
raise Exception("Lots of the latest integers are similar")
推荐阅读
- verilog - 4-bit counter using logic elements: output is always 0
- reactjs - 如何在 Typescript React.FC 中作为组件导入的 SVG 上使用 className
- google-data-studio - 数据洞察 - 按周分组
- javascript - 如何仅返回混合数组字符串中的置换数字?(Javascript)
- javascript - 选择值更改时,Jquery不会更改输入元素值
- amazon-ec2 - Rails 5.2.0 应用程序 Webpacker 需要 Yarn ">=1 <2" 并且您使用的是 Yarn v0.1.1 2011,弹性 beanstalk 部署失败
- angular - 如何使用其他网站的 Angular 应用程序
- typescript - 如何设置 TsServer 的语法分析行终止符类型?
- assembly - RISC管道对设置断点的影响?
- python - 如何从 python 的列中删除独立的字母?