在列表的开头查找相等元素的数量

时间:2014-11-07 06:23:59

标签: python list indexing

给出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])

我只是得到了' a'在x1中,而不是一行中的前导值的数量。如果有一个不需要知道第一个值的单个衬垫会很好。

3 个答案:

答案 0 :(得分:5)

itertools.groupby可以提供帮助...

from itertools import groupby

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

当然,我们可以把它变成1-liner(没有导入):

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

答案 1 :(得分: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))

答案 2 :(得分: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