简体   繁体   中英

Python group list by same numbers

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
}

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}

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.

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