1

嗨,我正在尝试计算列表中有多少次相邻值。为简化起见,我将在下面展示一个我正在寻找的示例:

我有一个 list= [2, 2, 2, 2, 1, 1, 0, 0, 0, 0, 1, 3, 2, 0, 2, 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
4

3 回答 3

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
于 2013-10-23T12:34:33.070 回答
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
于 2013-10-23T12:43:49.150 回答
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])
于 2013-10-23T12:41:47.557 回答