Python 如何查看列表是否包含连续数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33575235/
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 see if the list contains consecutive numbers
提问by allmine
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]
It should return True.
它应该返回 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.
如何在不修改原始列表的情况下检查列表是否包含最多 n 个连续数字?我想过复制列表并删除原始列表中出现的每个数字,如果列表为空,则它将返回 True。
Is there a better way to do this?
有一个更好的方法吗?
回答by wnnmaw
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.
这会保留原始列表,但如果您的列表特别长,则制作副本(然后排序)可能会很昂贵。
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)
请注意,在 Python 2 中,您可以简单地使用以下内容,因为range
返回了一个list
对象。在 3.x 及更高版本中,该函数已更改为返回一个range
对象,因此list
在与sorted(l)
sorted(l) == range(min(l), max(l)+1))
To check if n
entries are consecutive and non-repeating, it gets a little more complicated:
要检查n
条目是否连续且不重复,它会变得有点复杂:
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])
回答by Leb
The first code removes duplicates but keeps order:
第一个代码删除重复项但保持顺序:
from itertools import groupby, count
l = [1,2,4,5,2,1,5,6,5,3,5,5]
def remove_duplicates(values):
output = []
seen = set()
for value in values:
if value not in seen:
output.append(value)
seen.add(value)
return output
l = remove_duplicates(l) # output = [1, 2, 4, 5, 6, 3]
The next set is to identify which ones are in order, taken from here:
下一组是确定哪些是有序的,取自这里:
def as_range(iterable):
l = list(iterable)
if len(l) > 1:
return '{0}-{1}'.format(l[0], l[-1])
else:
return '{0}'.format(l[0])
l = ','.join(as_range(g) for _, g in groupby(l, key=lambda n, c=count(): n-next(c)))
l
outputs as: 1-2,4-6,3
l
输出为: 1-2,4-6,3
You can customize the functions depending on your output.
您可以根据输出自定义功能。
回答by Blender
Once you verify that the list has no duplicates, just compute the sum of the integers between min(l)
and max(l)
:
一旦您确认列表没有重复项,只需计算 和 之间的整数之min(l)
和max(l)
:
def check(l):
total = 0
minimum = float('+inf')
maximum = float('-inf')
seen = set()
for n in l:
if n in seen:
return False
seen.add(n)
if n < minimum:
minimum = n
if n > maximum:
maximum = n
total += n
if 2 * total != maximum * (maximum + 1) - minimum * (minimum - 1):
return False
return True
回答by PVNRT
I split your query into two parts part A "list contains up to n consecutive numbers" this is the first line if len(l) != len(set(l)):
我将您的查询分为两部分“列表最多包含 n 个连续数字”这是第一行 if len(l) != len(set(l)):
And part b, splits the list into possible shorter lists and checks if they are consecutive.
b 部分,将列表拆分为可能的较短列表并检查它们是否连续。
def example (l, n):
if len(l) != len(set(l)): # part a
return False
for i in range(0, len(l)-n+1): # part b
if l[i:i+3] == sorted(l[i:i+3]):
return True
return False
l = [1, 3, 5, 2, 4, 6]
print example(l, 3)
回答by Shankar
We can use known mathematics formula for checking consecutiveness, Assuming min number always start from 1
我们可以使用已知的数学公式来检查连续性,假设最小数总是从 1 开始
sum of consecutive n numbers 1...n = n * (n+1) /2
def check_is_consecutive(l):
maximum = max(l)
if sum(l) == maximum * (maximum+1) /2 :
return True
return False
回答by candles_and_oranges
import numpy as np
import pandas as pd
(sum(np.diff(sorted(l)) == 1) >= n) & (all(pd.Series(l).value_counts() == 1))
We test both conditions, first by finding the iterative difference of the sorted list np.diff(sorted(l))
we can test if there are n
consecutive integers. Lastly, we test if the value_counts()
are all 1, indicating no repeats.
我们测试这两个条件,首先通过找到排序列表的迭代差异,np.diff(sorted(l))
我们可以测试是否存在n
连续整数。最后,我们测试是否value_counts()
都是 1,表示没有重复。
回答by Bumperpants
Here is a really short easy solution without having to use any imports:
这是一个非常简单的解决方案,无需使用任何导入:
range = range(10)
L = [1,3,5,2,4,6]
L = sorted(L, key = lambda L:L)
range[(L[0]):(len(L)+L[0])] == L
>>True
This works for numerical lists of any length and detects duplicates. Basically, you are creating a range your list could potentially be in, editing that range to match your list's criteria (length, starting value) and making a snapshot comparison. I came up with this for a card game I am coding where I need to detect straights/runs in a hand and it seems to work pretty well.
这适用于任何长度的数字列表并检测重复项。基本上,您正在创建一个列表可能位于的范围,编辑该范围以匹配列表的条件(长度、起始值)并进行快照比较。我想出了这个用于我正在编码的纸牌游戏,我需要检测手牌中的直线/运行,它似乎工作得很好。
回答by Hooman Tamimi
def solution(A):
counter = [0]*len(A)
limit = len(A)
for element in A:
if not 1 <= element <= limit:
return False
else:
if counter[element-1] != 0:
return False
else:
counter[element-1] = 1
return True
回答by Alekhya Reddy
The input to this function is your list.This function returns False if the numbers are repeated. The below code works even if the list does not start with 1.
此函数的输入是您的列表。如果数字重复,此函数将返回 False。即使列表不是以 1 开头,下面的代码也能工作。
def check_is_consecutive(l):
"""
sorts the list and
checks if the elements in the list are consecutive
This function does not handle any exceptions.
returns true if the list contains consecutive numbers, else False
"""
l = list(filter(None,l))
l = sorted(l)
if len(l) > 1:
maximum = l[-1]
minimum = l[0] - 1
if minimum == 0:
if sum(l) == (maximum * (maximum+1) /2):
return True
else:
return False
else:
if sum(l) == (maximum * (maximum+1) /2) - (minimum * (minimum+1) /2) :
return True
else:
return False
else:
return True
回答by Aman
1.
1.
l.sort()
l.sort()
2.
2.
for i in range(0,len(l)-1))) print(all((l[i+1]-l[i]==1)
for i in range(0,len(l)-1))) print(all((l[i+1]-l[i]==1)