简体   繁体   English

Python 按相同编号分组列表

[英]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.我需要 python function 方面的帮助,如果它们被另一个数字分隔,它将计算列表中有多少重复数字。

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:您可以使用itertools.groupby收集连续数字和collections.Counter来统计它们:

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: 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.如果您需要解释,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM