您好,我正在尝试计算列表中相邻值的次数。为简化起见,我将在下面展示我正在寻找的示例:
我有一个输入列表 列表= [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
请您参考如下方法:
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
