我想编写一个python程序,它必须计算数组中相邻位置的重复元素。我想显示出现次数。
# Example
alist=[1,2,2,3,3,5,6] # ----- output - 4
alist=[1,2,3,4] # -------------output - 0
alist=[4,5,6,6,8,8,8,8] # -------output - 8
我试过
alist=[1,20,4,4,4,50];
i =0;
nextele=0;
temp=0;
while(i < len(alist)):
'print(alist[i])'
temp = alist[i];
nextele =alist[i+1];\\here i am getting error out of bound when it iterates last elelment
i=i+1;
提前致谢---
答案 0 :(得分:1)
在遍历列表时使用for x in range(len(aList)-1)
以防止获得IndexError
。比较aList[x]
和aList[x+1]
,如果它们相同,则将计数器增加2。
c=0
for x in range(len(aList)-1):
if aList[x]==aList[x+1]:
c+=2
答案 1 :(得分:1)
因为for循环中有alist[i+1]
,所以你不能通过列表直到结束,所以你必须在结束之前结束一个元素:
for i in range(len(alist)-1):
if(alist[i] == alist[i+1]):
counter+=2 # since you count both elements
alist=[1,2,2,3,3,5,6] # 4
alist=[4,5,6,6,8,8,8,8] # 8
答案 2 :(得分:1)
执行此操作的有效方法是将sum
与生成器表达式一起使用,alist
与alist[1:]
一起使用,以便我们可以比较alist
的相邻项。
data = [
[1, 2, 2, 3, 3, 5, 6],
[1, 2, 3, 4],
[4, 5, 6, 6, 8, 8, 8, 8],
[1, 20, 4, 4, 4, 50],
]
for alist in data:
a = sum(2 for u, v in zip(alist, alist[1:]) if u == v)
print(alist, a)
<强>输出强>
[1, 2, 2, 3, 3, 5, 6] 4
[1, 2, 3, 4] 0
[4, 5, 6, 6, 8, 8, 8, 8] 8
[1, 20, 4, 4, 4, 50] 4
如果您确实需要重复项目的总计数,则可以使用列表推导(或生成器表达式)和itertools.groupby
来查找重复的组,然后使用另一个生成器表达式来汇总包含更多项的组的长度超过1个元素。
from itertools import groupby
data = [
[1, 2, 2, 3, 3, 5, 6],
[1, 2, 3, 4],
[4, 5, 6, 6, 8, 8, 8, 8],
[1, 20, 4, 4, 4, 50],
]
for alist in data:
runs = [len(list(g)) for _, g in groupby(alist)]
repeats = sum(u for u in runs if u > 1)
print(alist, repeats)
<强>输出强>
[1, 2, 2, 3, 3, 5, 6] 4
[1, 2, 3, 4] 0
[4, 5, 6, 6, 8, 8, 8, 8] 6
[1, 20, 4, 4, 4, 50] 3
列表理解可以与生成器表达式结合使用:
for alist in data:
repeats = sum(u for u in (len(list(g)) for _, g in groupby(alist)) if u > 1)
print(alist, repeats)
答案 3 :(得分:0)
def get_count(num_list):
count=0
i=0
while(i<(len(num_list)-1)):
if(num_list[i]==num_list[i+1]):
count+=1
i+=1
return count
num_list=[1,1,5,100,-20,-20,6,0,0]
print(get_count(num_list))
答案 4 :(得分:-1)
lis=[0,1,1,0,1,2,2,3] #list declared
count=0 #count initialised
for i in range(len(lis)-1):
if lis[i]==lis[i+1]: #checking the value with the adjacent values
count+=1
print(count)