如何查看列表是否包含连续数字 [英] How to see if the list contains consecutive numbers
问题描述
我想测试列表是否包含连续的整数并且没有重复的数字. 例如,如果我有
I want to test if a list contains consecutive integers and no repetition of numbers. For example, if I have
l = [1, 3, 5, 2, 4, 6]
它应该返回True.
如何在不修改原始列表的情况下检查列表是否包含最多n个连续数字? 我考虑过复制列表并删除原始列表中出现的每个数字,如果列表为空,则它将返回True.
How should I check if the list contains up to n consecutive numbers without modifying the original list? I thought about copying the list and removing each number that appears in the original list and if the list is empty then it will return True.
有更好的方法吗?
推荐答案
对于整个列表,它应该与
For the whole list, it should just be as simple as
sorted(l) == list(range(min(l), max(l)+1))
这将保留原始列表,但是如果列表特别长,则进行复制(然后排序)可能会很昂贵.
This preserves the original list, but making a copy (and then sorting) may be expensive if your list is particularly long.
请注意,在Python 2中,您可以简单地使用以下内容,因为range
返回了list
对象.在3.x及更高版本中,该函数已更改为返回range
对象,因此在与sorted(l)
Note that in Python 2 you could simply use the below because range
returned a list
object. In 3.x and higher the function has been changed to return a range
object, so an explicit conversion to list
is needed before comparing to sorted(l)
sorted(l) == range(min(l), max(l)+1))
要检查n
条目是否连续且不重复,会变得有些复杂:
To check if n
entries are consecutive and non-repeating, it gets a little more complicated:
def check(n, l):
subs = [l[i:i+n] for i in range(len(l)) if len(l[i:i+n]) == n]
return any([(sorted(sub) in range(min(l), max(l)+1)) for sub in subs])
这篇关于如何查看列表是否包含连续数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!