Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jquery-ui/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检测列表中的连续整数[Python 3]_Python_Python 3.x - Fatal编程技术网

检测列表中的连续整数[Python 3]

检测列表中的连续整数[Python 3],python,python-3.x,Python,Python 3.x,我试图在列表中找到连续整数,类似于这个问题的解决方案: 然而,这个问题在Python2中得到了回答,在Python3中运行相同的代码示例将导致以下结果 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):

我试图在列表中找到连续整数,类似于这个问题的解决方案:

然而,这个问题在Python2中得到了回答,在Python3中运行相同的代码示例将导致以下结果

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))

我似乎看不出python版本之间的语法会发生什么变化,我猜我错过了一个简单的解决方案。

原来我没有充分阅读原始帖子,python 3的解决方案被发布在解决方案的注释中:


“将
lambda
更改为
lambda ix:ix[0]-ix[1]
,它在Python3和Python2中都能工作(当然,不包括打印语句)。–Kevin 5月20日15日4:17”

您可以这样编码

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()))

你很接近。请尝试
zip(data,data[1:])
上的groupby,我认为lambda只能接受一个参数,而该参数可能是一个元组。尝试
lambda t:t[0]-t[1]
@inspectorG4dget不幸地产生了相同的错误:
文件“temp.py”,groupby(zip(数据,数据[1:])中k,g的第4行,lambda(i,x):i-x:^SyntaxError:invalid syntax
@greenmaveguy我想这就是问题所在,在Python2和Python3之间,
lambda
是否发生了变化?我可以确认上面的代码在python上工作2@GreenCloakGuy你的解决方案奏效了,与我在原始帖子中错误忽略的解决方案非常相似。谢谢
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()))
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]