简体   繁体   English

迭代列表列表并在这些列表中查找连续的数字

[英]Iterate list of lists and finding consecutive numbers in those lists

currently I am trying to find consecutive numbers in a nested list. 目前,我正在尝试在嵌套列表中查找连续的数字。 My goal is the following example: 我的目标是以下示例:

nested = [ [1,7,13], [2,5,8], [3, 6, 9] ]

OUTPUT : (1,2,3), (7,8,9) 输出: (1,2,3), (7,8,9)

It should also work if there are more than three lists. 如果列表多于三个,它也应该起作用。 The amount of lists can vary. 列表的数量可以变化。

(Background for this; i am building a search engine for school and the numbers in nested are positions of the query words given by a user.) (为此,背景;我正在为学校建立搜索引擎,嵌套的数字是用户给出的查询词的位置。)

I have used : 我用过 :

def is_coherent(x):
    return all(np.diff(x) == 1)

to see if integers are consecutive. 查看整数是否连续。 Also i have experimented with itertools.izip. 我也尝试过itertools.izip。 However this does not allow me to change in the amount of lists i would like to iterate through. 但是,这不允许我更改要迭代的列表的数量。

Any help would be greatly appreciated! 任何帮助将不胜感激!

I think you want to get those items from cartesian product of the inner lists whose all items are continuous, for that you can try something like this: 我想您想从内部列表的笛卡尔积中获得所有项目都是连续的那些项目,为此,您可以尝试如下操作:

from itertools import izip, product

def find_continuous_items(data):
    for p in product(*data):
        if all(b-a==1 for a, b in izip(p, p[1:])):
            yield p

nested = [[1,7,13], [2,5,8], [3, 6, 9]]
print list(find_continuous_items(nested))
#[(1, 2, 3), (7, 8, 9)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM