本文介绍了如何在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中的任意列表中找到缺失的数字?
发布评论