如何在python 3中的任意列表中找到缺失的数字?

编程入门 行业动态 更新时间:2024-10-27 14:19:35
本文介绍了如何在python 3中的任意列表中找到缺失的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在任意列表中找到缺失的数字.在有序列表中,我的代码可以正常工作,但是在任意列表中,则不起作用.这是我的代码:

I am trying to find the missing numbers in an arbitrary list. In an ordered list my code works fine, but in an arbitrary list in doesn't work. This is my code:

a = [10,12,13,8] b = [x for x in range(a[0], a[-1] + 1)] a = set(a) print(list(a ^ set(b)))

输出为:

[8, 10, 12, 13]

但是对a进行排序时,输出结果很好:

But when a is sorted, the output comes out fine:

[9,11]

我的代码有什么问题,我该如何解决? PS.我知道我可以对列表进行排序,并解决问题,但我也希望它也适用于任意列表.

What's wrong in my code and how can i fix it? PS. I know i can just sort the list and get the problem fixed but i want it to work on an arbitary list as well.

推荐答案

这是怎么回事:

a = [10, 12, 13, 8] b = set(range(min(a), max(a)+1)) print(set(a).symmetric_difference(b))

更多推荐

如何在python 3中的任意列表中找到缺失的数字?

本文发布于:2023-11-29 19:25:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647398.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缺失   数字   如何在   列表中   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!