简体   繁体   中英

Find number of occurrences of groups of '-' sign in list in Python

it is my first question here.

I want to know how from this:

[1,1,2,'-','-',3,3,'-','-','-','-','-',5,5,'-','-','-']

find occurrences of '-' sign in this shape: [2,5,3]

you can use itertools groupby :

from itertools import groupby

l = [1, 1, 2, '-', '-', 3, 3, '-', '-', '-', '-', '-', 5, 5, '-', '-', '-']
result = [len(list(v)) for k, v in groupby(l) if k == '-']

OUTPUT:

[2, 5, 3]

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