Detecting consecutive integers in a list
From the docs:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i, x): i-x):
... print map(itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
You can adapt this fairly easily to get a printed set of ranges.
Find consecutive integers in a list
This is because you only check the next number. When you want the second number (like 9 or 3), you have to include a check for the previous number too. This will make the if
a bit longer, but it'll work.
num=[8,9,4,1,2,3]
for i in range(len(num)):
if (
( # check for the next number
i + 1 != len (num) and # don't check the end of the list
num[i]+1==num[i+1]
) or ( # check for the previous number
i != 0 and # don't check before the list
num [i-1] == num [i] - 1
)
): print('Con',num[i])
Also, I had to remove the -1
in your range, because I already do a manual check, and as pointed out, this prvented 3 from being shown.
Identify groups of continuous numbers in a list
more_itertools.consecutive_groups
was added in version 4.0.
Demo
import more_itertools as mit
iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
[list(group) for group in mit.consecutive_groups(iterable)]
# [[2, 3, 4, 5], [12, 13, 14, 15, 16, 17], [20]]
Code
Applying this tool, we make a generator function that finds ranges of consecutive numbers.
def find_ranges(iterable):
"""Yield range of consecutive numbers."""
for group in mit.consecutive_groups(iterable):
group = list(group)
if len(group) == 1:
yield group[0]
else:
yield group[0], group[-1]
iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]
list(find_ranges(iterable))
# [(2, 5), (12, 17), 20]
The source implementation emulates a classic recipe (as demonstrated by @Nadia Alramli).
Note: more_itertools
is a third-party package installable via pip install more_itertools
.
Detecting Consecutive Integers in a list [Python 3]
Turns out I didn't read the original post enough, a solution for python 3 was posted in a comment to the solution:
"Change the lambda
to lambda ix : ix[0] - ix[1]
and it works in both Python 3 and Python 2 (well, not counting the print statement). – Kevin May 20 '15 at 4:17"
Detecting consecutive integers and collapse to string
int[] numbers = { 1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14 };
return string.Join(", ",
numbers
.Select((n, i) => new { value = n, group = n - i })
.GroupBy(o => o.group)
.Select(g => g.First().value + "-" + g.Last().value)
);
Find pairs of consecutive integers in array PYTHON
In response to the more recent clarifications:
def find_pairs(xs):
result = []
i = 0
while i < len(xs) - 1:
if xs[i] == xs[i + 1]:
result.append(xs[i])
i += 1
i += 1
return result
Testing:
>>> xs = [3, 4, 4, 4, 5, 6, 6, 5, 4, 4]
>>> find_pairs(xs)
[4, 6, 4]
Update: Minor off-by-one bug fix.
Identify if list has consecutive elements that are equal
You can use itertools.groupby()
and a generator expression within any()
*:
>>> from itertools import groupby
>>> any(sum(1 for _ in g) > 1 for _, g in groupby(lst))
True
Or as a more Pythonic way you can use zip()
, in order to check if at least there are two equal consecutive items in your list:
>>> any(i==j for i,j in zip(lst, lst[1:])) # In python-2.x,in order to avoid creating a 'list' of all pairs instead of an iterator use itertools.izip()
True
Note: The first approach is good when you want to check if there are more than 2 consecutive equal items, otherwise, in this case the second one takes the cake!
* Using sum(1 for _ in g)
instead of len(list(g))
is very optimized in terms of memory use (not reading the whole list in memory at once) but the latter is slightly faster.
Find consecutive strings representing numbers in a Python list
Try something like this:
l = ['1133', '1300', '1418', '1443', '1473', '1600', '1601', '1988', '1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997', '1998', '2000', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2012', '2013', '2014', '2015', '2153', '2600', '3000', '3714', '3785', '3896', '3995', '4001', '4436', '5094', '5346', '8000']
size = len(l)
i = 0
while i < size:
j = i
while j + 1 < size and int(l[j]) + 1 == int(l[j + 1]):
j += 1
if j != i:
print (l[i:j+1])
i = j + 1
Output:
['1600', '1601']
['1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997', '1998']
['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010']
['2012', '2013', '2014', '2015']
Related Topics
How to Allow or Deny Notification Geo-Location Microphone Camera Pop Up
How to Make a Multi-Color Line in Matplotlib
How to Save a Python Interactive Session
What Is the Use of Join() in Python Threading
How to Drop a List of Rows from Pandas Dataframe
Difference Between Exit() and Sys.Exit() in Python
Efficient Way to Apply Multiple Filters to Pandas Dataframe or Series
Creating a New Corpus with Nltk
Python List Subtraction Operation
How to Run a Python Program in the Command Prompt in Windows 7
How to Mock an Open Used in a with Statement (Using the Mock Framework in Python)
Convert Unicode to Ascii Without Errors in Python
Python Pandas: Apply a Function with Arguments to a Series
Type Hints: Solve Circular Dependency
Why Isn't Pycharm's Autocomplete Working for Libraries I Install
How to Execute Raw SQL in Flask-Sqlalchemy App