Python:找出整数列表是否一致

标签 python sequence python-itertools

我试图找出一个整数列表是连贯的还是“一气呵成”的,这意味着两个相邻元素之间的差值必须恰好为 1,并且数字必须单调递增。我 found一种巧妙的方法,我们可以按列表中的数字减去列表中元素的位置进行分组——当数字不一致时,这种差异会发生变化。显然,当序列不包含间隙或重复时,应该只有一组。

测试:

>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [1, 2, 3, 4, 5, 7]
>>> l3 = [1, 2, 3, 4, 5, 5]
>>> l4 = [1, 2, 3, 4, 5, 4]
>>> l5 = [6, 5, 4, 3, 2, 1]
>>> def is_coherent(seq):
...     return len(list(g for _, g in itertools.groupby(enumerate(seq), lambda (i,e): i-e))) == 1
... 
>>> is_coherent(l1)
True
>>> is_coherent(l2)
False
>>> is_coherent(l3)
False
>>> is_coherent(l4)
False
>>> is_coherent(l5)
False

效果不错,但我个人觉得,考虑到问题的简单性,这个解决方案有点太绕了。您能否想出一种更清晰的方法来实现相同的目标而不显着增加代码长度?

编辑:答案摘要

根据下面给出的答案,解决方案

def is_coherent(seq):
    return seq == range(seq[0], seq[-1]+1)

显然赢了。对于小列表(10^3 个元素),它比 groupby 方法快 10 倍,并且(在我的机器上)仍然比下一个最佳方法(使用 izip_longest).它的缩放行为最差,但即使对于包含 10^8 个元素的大型列表,它仍然比下一个最佳方法快两倍,这也是基于 izip_longest 的解决方案。

timeit获取的相关计时信息:

Testing is_coherent_groupby...
   small/large/larger/verylarge duration: 8.27 s, 20.23 s, 20.22 s, 20.76 s
   largest/smallest = 2.51
Testing is_coherent_npdiff...
   small/large/larger/verylarge duration: 7.05 s, 15.81 s, 16.16 s, 15.94 s
   largest/smallest = 2.26
Testing is_coherent_zip...
   small/large/larger/verylarge duration: 5.74 s, 20.54 s, 21.69 s, 24.62 s
   largest/smallest = 4.28
Testing is_coherent_izip_longest...
   small/large/larger/verylarge duration: 4.20 s, 10.81 s, 10.76 s, 10.81 s
   largest/smallest = 2.58
Testing is_coherent_all_xrange...
   small/large/larger/verylarge duration: 6.52 s, 17.06 s, 17.44 s, 17.30 s
   largest/smallest = 2.65
Testing is_coherent_range...
   small/large/larger/verylarge duration: 0.96 s, 4.14 s, 4.48 s, 4.48 s
   largest/smallest = 4.66

测试代码:

import itertools
import numpy as np
import timeit


setup = """
import numpy as np
def is_coherent_groupby(seq):
    return len(list(g for _, g in itertools.groupby(enumerate(seq), lambda (i,e): i-e))) == 1

def is_coherent_npdiff(x):
    return all(np.diff(x) == 1)

def is_coherent_zip(seq):
    return all(x==y+1 for x, y in zip(seq[1:], seq))

def is_coherent_izip_longest(l):
    return all(a==b for a, b in itertools.izip_longest(l, xrange(l[0], l[-1]+1)))

def is_coherent_all_xrange(l):
    return all(l[i] + 1 == l[i+1] for i in xrange(len(l)-1))

def is_coherent_range(seq):
    return seq == range(seq[0], seq[-1]+1)


small_list = range(10**3)
large_list = range(10**6)
larger_list = range(10**7)
very_large_list = range(10**8)
"""


fs = [
    'is_coherent_groupby',
    'is_coherent_npdiff',
    'is_coherent_zip',
    'is_coherent_izip_longest',
    'is_coherent_all_xrange',
    'is_coherent_range'
    ]


for n in fs:
    print "Testing %s..." % n
    t1 = timeit.timeit(
        '%s(small_list)' % n, 
        setup,
        number=40000
        )      
    t2 = timeit.timeit(
        '%s(large_list)' % n, 
        setup,
        number=100
        )     
    t3 = timeit.timeit(
        '%s(larger_list)' % n, 
        setup,
        number=10
        )
    t4 =  timeit.timeit(
        '%s(very_large_list)' % n, 
        setup,
        number=1
        )
    print "   small/large/larger/verylarge duration: %.2f s, %.2f s, %.2f s, %.2f s" % (t1, t2, t3, t4)
    print "   largest/smallest = %.2f" % (t4/t1)

测试机:

  • Linux 3.2.0 (Ubuntu 12.04)
  • Python 2.7.3 (gcc 4.1.2)
  • 使用 Intel 编译器构建的 numpy 1.6.2
  • CPU:E5-2650 @ 2.00GHz
  • 24 GB 内存

最佳答案

怎么样

sorted_list = sorted(my_list)
return sorted_list == range(sorted_list[0],sorted_list[-1]+1)

或者如果它已经排序就只有连贯性了

return my_list == range(my_list[0],my_list[-1]+1)

如果您使用的是 python 3,则需要 list(range(...))

关于Python:找出整数列表是否一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18131741/

相关文章:

java - 适用于多个 api 类的 Google Endpoints Android 客户端库

sql - 甲骨文日期序列?

postgresql - 一些序列不在 pg_dump 的转储中

Python - 使用特定字母表的 n 个替换构建特定长度的新字符串

python - 使用装饰器为装饰函数添加一个参数

python - Python中如何动态加载类并调用方法?

python - debian 8.2 中的 "pip is configured with locations that require TLS/SSL"

python - 主 ID 序列不递增

python - 如何获取列表的所有可能顺序

python - 将参数传递给 itertools.groupby() 中的 key 函数以计算键的唯一值