开发者

python: comparing this row with next row

c1 is a list of lists like this:

c1=[[1,2,3],[1,2,6],[7,8,6]]

for row in c1:

i want to开发者_Go百科 keep track of whether there is a change in row[0]

for example:

in [1, 2, 3] and [1, 2, 6] there is no change in row[0]

however in [1, 2, 6] and [ 7, 8, 6] there is a change in row[0]

how do i catch this change? also i would like to know which row this changed occurred at


If you had matrix data you basically want a diff of the first "column". You probably want to report the changes and the location of the changes and probably want to store them sparsely:

c1=[[1,2,3],[1,2,6],[7,8,6]]
ans=[]    # a list of [indices,differences]
col=0
for i in range(len(c1)-1):
    diff = c1[i+1][col]-c1[i][col]
    if diff!=0:
        ans.append([i,diff])


Use a variable to keep track of the previous item.

prev = None
for row in c1:
  if prev is not None and prev != row[0]:
     # there is a change
  prev = row[0]

...just make sure you use a nonexistent value as the starting value (if your lists may contain anything, use an extra flag for the first item). If you want the first row to be considered a change, change the if to:

if prev is None or prev != row[0]:


>>> from operator import itemgetter
>>> from itertools import groupby
>>> c1=[[1,2,3],[1,2,6],[7,8,6]]
>>> list(groupby(c1,itemgetter(0)))
[(1, <itertools._grouper object at 0xa6f8d0>), (7, <itertools._grouper object at 0xa6f890>)]

this is simply saying group the elements of c1 by the first item of each element

You can also expand the result as a nested list to see how the items are grouped

>>> [(x,list(y)) for x,y in (groupby(c1,itemgetter(0)))]
[(1, [[1, 2, 3], [1, 2, 6]]), (7, [[7, 8, 6]])]

to get the row of the change, you can look at the length of the first element of the result

>>> len(list(next(groupby(c1,itemgetter(0)))[1]))
2


I've posted this as a separate answer to avoid making the other answer too jumbled

>>> for i in range(1,len(c1)):
...  if c1[i-1][0]!=c[i][0]: break
...
>>> print i
2


Print a list of all rows with a different first element than its predecessor:

import itertools

c1=[[1,2,3],[1,2,6],[7,8,6]]

xs, ys = itertools.tee(c1)
next(ys)
print [y for x, y in itertools.izip(xs, ys) if x[0] != y[0]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜