Python Check how many times item appears in a row in list -


if have list, say

 lst = [1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0] 

i'm trying find way show amount of times in row each item appears, return list afterwards

lstnew = [(1, 4), (0, 2), (1, 1), (0, 4), (1, 3), (0, 2)] 

thanks in advance. (the outputed data format not matter much, if it's easier return dict go ahead)

you can use groupby

from itertools import groupby [(a, len(list(b))) a, b in groupby(lst)] 

result:

[(1, 4), (0, 2), (1, 1), (0, 4), (1, 3), (0, 2)] 

group group consecutive elements of same value , len(list(...)) can take length of group. 1 advantage of method, it'll run in linear time.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -