Python:确定列表中相等项的序列长度 [英] Python: determine length of sequence of equal items in list

查看:21
本文介绍了Python:确定列表中相等项的序列长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表如下:

l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]

我想确定一系列相等项的长度,即对于给定的列表,我希望输出为:

I want to determine the length of a sequence of equal items, i.e for the given list I want the output to be:

[(0, 6), (1, 6), (0, 4), (2, 3)]

(或类似格式).

我考虑过使用 defaultdict 但它计算每个项目的出现次数并将其累积到整个列表中,因为我不能有多个键0".

I thought about using a defaultdict but it counts the occurrences of each item and accumulates it for the entire list, since I cannot have more than one key '0'.

现在,我的解决方案是这样的:

Right now, my solution looks like this:

out = []
cnt = 0

last_x = l[0]  
for x in l:
    if x == last_x:
        cnt += 1
    else:
        out.append((last_x, cnt))
        cnt = 1
    last_x = x
out.append((last_x, cnt))

print out

我想知道是否有更pythonic的方法来做到这一点.

I am wondering if there is a more pythonic way of doing this.

推荐答案

您几乎肯定想使用 itertools.groupby:

l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
    answer.append((key, len(list(iter))))

# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]

如果你想让它的内存效率更高,但又增加了更多的复杂性,你可以添加一个长度函数:

If you want to make it more memory efficient, yet add more complexity, you can add a length function:

def length(l):
    if hasattr(l, '__len__'):
        return len(l)
    else:
        i = 0
        for _ in l:
            i += 1
        return i

l = [0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,2,2,2]
answer = []
for key, iter in itertools.groupby(l):
    answer.append((key, length(iter)))

# answer is [(0, 6), (1, 6), (0, 4), (2, 3)]

请注意,虽然我没有对 length() 函数进行基准测试,但它很可能会减慢您的速度.

Note though that I have not benchmarked the length() function, and it's quite possible it will slow you down.

这篇关于Python:确定列表中相等项的序列长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆