寻找列表开头相同元素的数量

3

给定一个Python列表,我想找出列表开头有多少个相等的元素。

例如输入:

x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']

一些神奇的函数(或一行代码)将输出:

f(x1) = 2 # There are 2 'a' values in the beginning.
f(x2) = 3 # There are 3 1-values in the beginning.
f(x3) = 1 # Only 1 'foo' in beginning.

如果我这样做:
sum([1 if x=='a' else 0 for x in x1])

我只是得到了x1中'a'出现的次数,而不是一行中前导值的数量。希望有一个一行代码,不需要知道第一个值,能够完成这个任务。
3个回答

5

itertools.groupby can help ...

from itertools import groupby

def f(lst):
    if_empty = ('ignored_key', ())
    k, v = next(groupby(lst), if_empty)
    return sum(1 for _ in v)

当然,我们可以将其转换为一行代码(不包括导入):
sum(1 for _ in next(groupby(lst), ('ignored', ()))[1])

但我并不真正推荐这样做。

演示:

>>> from itertools import groupby
>>> 
>>> def f(lst):
...     if_empty = ('ignored_key', ())
...     k, v = next(groupby(lst), if_empty)
...     return sum(1 for _ in v)
... 
>>> f(x1)
2
>>> f(x2)
3
>>> f(x3)
1
>>> f([])
0

谢谢!这很完美。 - nfmcclure

3
你可以使用 takewhile
import itertools

xs = [1, 1, 1, 3, 1, 1, 1, 8]

sum(1 for _ in itertools.takewhile(lambda x: x == xs[0], xs))

在一个函数中:

def count_first(iterable):
    i = iter(iterable)
    first = next(i)
    return 1 + sum(1 for _ in itertools.takewhile(lambda x: x == first, i))

1
也许更好的方法是检查第一个不等于第一个值的出现:
x1 = ['a','a','b','c','a','a','a','c']
x2 = [1, 1, 1, 3, 1, 1, 1, 8]
x3 = ['foo','bar','foobar']
x4 = []
x5 = [1,1,1,1,1,1]

def f(x):
    pos = -1
    for pos,a in enumerate(x):
        if a!=x[0]:
            return pos
    return pos+1


print(f(x1))
print(f(x2))
print(f(x3))
print(f(x4))
print(f(x5))

2
3
1
0
6

简洁明了。谢谢。 - nfmcclure

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接