我正在使用

Python并考虑以下问题:给出一个列表,例如[1,0,-2,0,0,4,5,0,3]多次包含0的整数,我希望有这些0和每一个的索引是它出现在列表中的次数,直到出现不同的元素或列表结束.

给定l = [1,0,-2,0,0,4,5,0],函数将返回((1,1),(3,2),(7,1)).结果是一个元组列表.元组的第一个元素是给定元素的索引(在列表中),第二个元素是在不同元素出现或列表结束之前重复的次数.

天真地,我会写这样的东西:

def myfun(l, x):

if x not in l:

print(“The given element is not in list.”)

else:

j = 0

n = len(l)

r = list()

while j <= (n-2):

count = 0

if l[j] == x:

while l[j + count] == x and j <= (n-1):

count +=1

r.append((j, count))

j += count

else:

j += 1

if l[-1] == x:

r.append((n-1, 1))

return r

但我想知道是否会有更好的(更短的?)方式做同样的事情.


版权声明:本文为weixin_39617006原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_39617006/article/details/112882920