Home > OS >  Python group list by same numbers
Python group list by same numbers

Time:11-27

I need help with python function, which will count for me how many repeated numbers on list, if they are separated by another number.

nums = [3, 1, 2, 3, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 1, 2]

should return

{
[3]: 2,
[1]: 3,
[2]: 5,
[1, 1]: 2,
[2, 2, 2, 2]: 1
}

CodePudding user response:

You can use itertools.groupby to collect the consecutive numbers and collections.Counter to count them:

nums = [3, 1, 2, 3, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 1, 2]

from itertools import groupby
from collections import Counter
dict(Counter(tuple(g) for k,g in groupby(nums)))

NB. You cannot use lists as dictionary keys, I've used tuples instead

Output:

{(3,): 2,
 (1,): 3,
 (2,): 5,
 (1, 1): 2,
 (2, 2, 2, 2): 1}

CodePudding user response:

Note that you cannot have a list as a key. Instead, we can use a string.

This returns all lengths of streaks, not just max and min. Say in comments if you would like otherwise.

nums = [3, 1, 2, 3, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 1, 2]
results = {}
streak = 0
previous = None
for num in nums:
    print(num)
    if previous != num:
        streak = 0
    streak  = 1
    previous = num
    for i in range(1, streak   1):
        results[str(num)*i] = results.get(str(num)*i, 0)   1

Please comment if you would like an explanation.

  • Related