Python 如何从列表中找到缺失的数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20718315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find a missing number from a list?
提问by Rajeev
采纳答案by Abhijit
>>> a=[1,2,3,4,5,7,8,9,10]
>>> sum(xrange(a[0],a[-1]+1)) - sum(a)
6
alternatively (using the sum of AP series formula)
或者(使用 AP 系列公式的总和)
>>> a[-1]*(a[-1] + a[0]) / 2 - sum(a)
6
For generic cases when multiple numbers may be missing, you can formulate an O(n) approach.
对于可能缺少多个数字的一般情况,您可以制定 O(n) 方法。
>>> a=[1,2,3,4,7,8,10]
>>> from itertools import imap, chain
>>> from operator import sub
>>> print list(chain.from_iterable((a[i] + d for d in xrange(1, diff))
for i, diff in enumerate(imap(sub, a[1:], a))
if diff > 1))
[5, 6, 9]
回答by Gabriel
1 + 2 + 3 + ... + (n - 1) + n = (n) * (n + 1)/2
so the missing number is:
所以缺少的数字是:
(a[-1] * (a[-1] + 1))/2 - sum(a)
回答by Sa?a ?ijak
set(range(a[len(a)-1])[1:]) - set(a)
Take the set of all numbers minus the set of given.
取所有数字的集合减去给定的集合。
回答by ndpu
If many missing numbers in list:
如果列表中缺少许多数字:
>>> a=[1,2,3,4,5,7,8,10]
>>> [(e1+1) for e1,e2 in zip(a, a[1:]) if e2-e1 != 1]
[6, 9]
回答by jonrsharpe
A simple list comprehension approach that will work with multiple (non-consecutive) missing numbers.
一种简单的列表理解方法,适用于多个(非连续)缺失数字。
def find_missing(lst):
"""Create list of integers missing from lst."""
return [lst[x] + 1 for x in range(len(lst) - 1)
if lst[x] + 1 != lst[x + 1]]
回答by Jon Clements
And another itertoolsway:
而另一种itertools方式:
from itertools import count, izip
a=[1,2,3,4,5,7,8,9,10]
nums = (b for a, b in izip(a, count(a[0])) if a != b)
next(nums, None)
# 6
回答by M4rtini
set(range(1,a[-1])) | set(a)
Compute the union of two sets.
计算两个集合的并集。
回答by Prat_yow
def find(arr):
for x in range(0,len(arr) -1):
if arr[x+1] - arr[x] != 1:
print arr[x] + 1
回答by Samman Thapa
This should work:
这应该有效:
a = [1,3,4,5, 7,8, 9, 10]
b = [x for x in range(a[0], a[-1] + 1)]
a = set(a)
print (list(a ^ set(b)))`
>> [2,6]
回答by Andre
I used index position. this way i compare index and value.
我使用了索引位置。这样我比较指数和价值。
a=[0,1,2,3,4,5,7,8,9,10]
for i in a:
print i==a.index(i)

