[英]Detecting Consecutive Integers in a list [Python 3]
I'm trying to find consecutive integers in a list, similar to the solution to this question: Detecting consecutive integers in a list我正在尝试在列表中查找连续整数,类似于此问题的解决方案: Detecting Continuous integers in a list
However, that question was answered in python 2, and running the same code sample in python 3 results in the following但是,这个问题在 python 2 中得到了回答,在 python 3 中运行相同的代码示例会导致以下结果
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))
File "temp.py", line 4
for k, g in groupby(enumerate(data), lambda (i, x): i-x):
^
SyntaxError: invalid syntax
I can't seem to see where the syntax would have changed between python versions, and I'm guessing I'm missing an easy fix.我似乎看不到 python 版本之间的语法会发生什么变化,我猜我错过了一个简单的修复。
Turns out I didn't read the original post enough, a solution for python 3 was posted in a comment to the solution:原来我没有足够阅读原始帖子,在对解决方案的评论中发布了 python 3 的解决方案:
"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" “将
lambda
更改为lambda ix : ix[0] - ix[1]
并且它适用于 Python 3 和 Python 2(好吧,不包括打印语句)。– Kevin 2015 年 5 月 20 日 4:17”
In [16]: data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
In [17]: data
Out[17]: [1, 4, 5, 6, 10, 15, 16, 17, 18, 22, 25, 26, 27, 28]
In [18]: def groups(L):
...: temp = [L[0]]
...: for num in L[1:]:
...: if num != temp[-1]+1:
...: yield temp
...: temp = []
...: temp.append(num)
...: yield temp
...:
In [19]: for run in groups(data): print(run)
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
You can code like this;你可以这样编码;
from itertools import groupby
data = [1, 4, 5, 6, 10, 15, 16, 17, 18, 22, 25, 26, 27, 28]
for k, g in groupby(enumerate(data), lambda x : x[0] - x[1]):
print(list(dict(g).values()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.