Python-查找列表中相邻值的数量

时间:2013-10-23 12:28:47

标签: python dictionary

您好我正在尝试计算列表中有相邻值的次数。为了简化,我将在下面展示我正在寻找的一个例子:

我有一个输入列表 list = [2,2,2,2,1,1,0,0,0,0,1,3,2,0,2,0,0,0,0]和 我想输出3,因为2,2,2,2 1,1和2,2是相等的相邻值。 (忽略零)。

我能用字典解决这个问题吗?

dict={}
list= [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]     

for x in range(1, len(list)):
    if list[x]=0:
         pass
    elif list[x]=list[x-1]:
          dict          #this is the part I'm having trouble implementing

3 个答案:

答案 0 :(得分:6)

myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
import itertools
print sum(1 for key, group in itertools.groupby(myList) if len(list(group)) > 1 and key)

可读形式:

print sum(1
          for key, group in itertools.groupby(myList)
          if len(list(group)) > 1 and key)

<强>输出

3

修改:如果您不想使用上述方法,

myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
previous, count, result = myList[0], 0, 0
for num in myList[1:]:
    if num == 0: continue
    if previous != num:
        if count:
            result += 1
        previous = num
        count = 0
    else:
        count += 1
if count: result += 1
print result

<强>输出

3

修改1:根据您在评论部分中的请求,

myList = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
import itertools
groupedItems = [list(group) for key, group in itertools.groupby(myList) if key]
groupedItemsSizes = [len(item) for item in groupedItems if len(item) > 1]
print len(groupedItemsSizes)             # Number of repeating groups
print float(sum(groupedItemsSizes))/len(groupedItemsSizes)  # Mean

<强>输出

3
2.66666666667

答案 1 :(得分:1)

这是一个可以产生连续项目及其计数的函数。

def count_consequtive_items(lst, exclude=[0], reset_after_pass=True):
    prev = None
    count = 0
    for item in lst:
        if item in exclude:
            if prev and count:
                yield prev, count
            if reset_after_pass:
                prev = None
                count = 0
            continue
        if item != prev and count:
            yield prev, count
            count = 0
        count += 1
        prev = item
    if prev and count:
        yield prev, count

使用它:

>>> numbers = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]            
>>> list(count_consequtive_items(numbers))
[(2, 4), (1, 2), (1, 1), (3, 1), (2, 1), (2, 2)]

然后你可以计算有多少人的数量高于1:

>>> len([x for x in count_consequtive_items(numbers) if x[1] > 1])
3

当然,你可以使用itertools.groupby

>>> numbers = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]
>>> from itertools import groupby
>>> len([g for g,l in groupby(numbers) if len(list(l)) > 1 and g != 0])
3

答案 2 :(得分:0)

import itertools

lst = [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 2, 0, 0, 0, 0]

tran_1 =  [list(group) for key, group in itertools.groupby(lst)]

print sum([1 for ele in tran_1 if ele[0] and len(ele) > 1])