foo = ['bar', 'bar', 'bar', 'foo', 'foo','bar']
def my_groupby(l):
first, last, current_value = 0, 0, l[0]
for i, value in enumerate(l):
if value != current_value:
yield first + 1, last + 1, current_value
current_value, first, last = value, i, i
else:
last = i
yield first + 1, last + 1, current_value
for first, last, value in my_groupby(foo):
if first != last:
print(f'{first}-{last} = {value}')
else:
print(f'{first} = {value}')
一种可能的解决方案(没有来自
itertools
的groupby
):印刷品:
这将输出:
不清楚你到底想要什么,但你可以数元素
或者
相关问题 更多 >
编程相关推荐