[英]Hey everyone, I was just wondering what was wrong with my code?
Im trying to create a function that records the amount of times a value in a list is repeated in a row.我试图创建一个 function 来记录列表中的值在一行中重复的次数。 After about an hour of deliberation, I was able to reach a stable-looking conclusion, yet i am unable to receive the desired outcome
经过大约一个小时的考虑,我得出了一个看似稳定的结论,但我无法得到想要的结果
lst = [1,2,2,2,3,1,1]
def compress(numlist):
intervals,x=0,0
for i in numlist:
if i == numlist[x]:
intervals+=1
elif i != numlist[x]:
print((intervals,numlist[x]), end=" ")
x+=intervals
intervals=1
compress(lst)
Here, I was trying to get the function to "compress" the list of integers When I run the code, the outcome is:在这里,我试图让 function 来“压缩”整数列表当我运行代码时,结果是:
(1, 1) (3, 2) (1, 3)
While the desired outcome is:虽然期望的结果是:
(1, 1) (3, 2) (1, 3) (2,1)
You only show a run when you find a value that is not equal to the previous one.只有当您发现一个值不等于前一个值时,您才显示运行。 There is no value after the last value, of course, so the last run is never printed.
当然,最后一个值之后没有任何值,因此永远不会打印最后一次运行。 Just add a line after the loop to print the last run.
只需在循环后添加一行即可打印最后一次运行。
if intervals != 0:
print((intervals,numlist[x]))
By the way, you don't need the elif
conditional.顺便说一下,你不需要
elif
条件。 All you need there is an else
, since if i == numlist[x]
, then the only other thing possible is i != numlist[x]
.您只需要一个
else
,因为如果i == numlist[x]
,那么唯一可能的就是i != numlist[x]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.