Skip to content Skip to sidebar Skip to footer

Python: Find Sequential Change In One Member Of List Pairs, Report Other

There must be a simpler, more pythonic way of doing this. Given this list of pairs: pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] How do I most easily find the first item in adj

Solution 1:

import itertools as it

pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]

# with normal zip and slicingfor a,b inzip(pp,pp[1:]):
    if a[1] != b[1]:
        x=(a[0],b[0])
        print x
        break# with generators and izip
iterfirst = (b for a,b in pp)
itersecond = (b for a,b in pp[1:])
iterfirstsymbol = (a for a,b in pp)
itersecondsymbol = (a for a,b in pp[1:])
iteranswer = it.izip(iterfirstsymbol, itersecondsymbol, iterfirst, itersecond)

printnext((symbol1, symbol2)
           for symbol1,symbol2, first, second in iteranswer
           if first != second)

Added my readable generator version.

Solution 2:

You could try somethingl like :

[[pp[i][0],pp[i+1][0]]for i in xrange(len(pp)-1) if pp[i][1]!=pp[i+1][1]][0]

(using list comprehension)

Solution 3:

try comparing pp[:-1] to pp[1:], something like

[a for a in zip(pp[:-1], pp[1:]) if a[0][1] != a[1][1]]

(look at zip(pp[:-1], pp[1:]) first to see what's going on

edit:

i guess you'd need

([a[0][0], a[1][0]] for a inzip(pp[:-1], pp[1:]) if a[0][1] != a[1][1]).next()

Solution 4:

>>>import itertools>>>pp = [('a',1),('b',1),('c',1),('d',2),('e',2)]>>>gb = itertools.groupby(pp, key=lambda x: x[1])>>>f = lambda x: list(next(gb)[1])[x][0]>>>f(-1), f(0)
('c', 'd')

Solution 5:

Here is something (simple?) with recursion:

deffirst_diff( seq, key=lambda x:x ):
    """ returns the first items a,b of `seq` with `key(a) != key(b)` """
    it = iter(seq)
    deftest(last): # recursive function
        cur = next(it)
        if key(last) != key(cur):
            return last, cur
        else:
            return test(cur)
    return test(next(it))

print first_diff( pp, key=lambda x:x[1]) # (('c', 1), ('d', 2))

Post a Comment for "Python: Find Sequential Change In One Member Of List Pairs, Report Other"