简体   繁体   中英

Python3 find groups of strictly increasing “ float values” within a list

I cannot find a solution to find groups of strictly increasing "float values" within a list. All examples I find online are all group by "integers" type values. A simple example of what I am looking for is code that picks up the float value sequence as well...see my list below for clarity:

l = [8, 9, 10, -1.2, -1.1,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]

the code below returns only the integer numbers and simply ignores the floats. If I would use the "round" function to change the list into integers, it would defeat the whole purpose of the effort...

What I would like to achieve is an output of strictly increasing "float values" from the list above returning the output values of: [[8, 9, 10],[-1.2,-1.1,-1.0], [7, 8], [1.2, 2.3, 3.4]]

Code to explain the problem best:

def groupSequence(x): 
    it = iter(x) 
    prev, res = next(it), [] 
  
    while prev is not None: 
        start = next(it, None) 
  
        if prev + 1 == start: 
            res.append(prev) 
        elif res: 
            yield list(res + [prev]) 
            res = [] 
        prev = start 

l = [8, 9, 10, -1.2, -1.1 ,-1.0, -10, -11, -12, 7, 8, 1.2, 2.3, 3.4]
print(list(groupSequence(l)))

#current output: [[8, 9, 10], [7, 8]]

#desired output [[8, 9, 10],[-1.2,-1.1,-1.0], [7, 8], [1.2, 2.3, 3.4]]

Any help would be much appreciated.

The problem is in this line:

if prev + 1 == start:

The floats in your sequence doesn't increase by one: -1.2 + 1 <> -1.1

if start and start > prev:

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