简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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