Gokulkrishna Surapureddy Gokulkrishna Surapureddy - 1 year ago 75
Python Question

How to find length of the sequence in a list using python [with Duplicates]?

I am trying with below code.

from itertools import groupby

range_mod = ['P', 'P', 'P', 'P', 'N', 'N', 'N', 'N', 'P', 'P', 'P']

print(dict((i,len(list(j))) for i, j in groupby(range_mod)))

Note: Output need not be in Dict

Actual Output:

{'P': 3, 'N': 4}

Expected output: I am aware Dictionary doesn't allow duplicate keys. So looking for other options

{'P': 4, 'N': 4, 'P' : 3}

Thanks in advance.

Answer Source
>>> print(list((i,len(list(j))) for i, j in groupby(range_mod)))
[('P', 4), ('N', 4), ('P', 3)]

How about this? ^

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download