我正在使用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
Run Code Online (Sandbox Code Playgroud)
但我想知道是否会有更好的(更短的?)方式做同样的事情.
不是最漂亮的,但只是一句台词:
>>> import itertools
>>> l=[1, 0, -2, 0, 0, 4, 5, 0]
>>> [(k[0][0],len(k)) for k in [list(j) for i,j in itertools.groupby(enumerate(l), lambda x: x[1]) if i==0]]
[(1, 1), (3, 2), (7, 1)]
Run Code Online (Sandbox Code Playgroud)
首先,itertools.groupby(enumerate(l), lambda x: x[1])将按 的第二项进行分组enumerate(l),但保留该项目的索引。
然后[list(j) for i,j in itertools.groupby(enumerate(l), lambda x: x[1]) if i==0]将仅保留 0 值。
最后,需要最后一个列表理解,因为list(j)消耗了 itertools 对象。