l = [1, 2, 3]
count = 0 # count current number of continuous 0
out = [0]
for i in range(len(l)):
if l[i] == 0: # if the number is 0 increase current group counter
count += 1
elif count == 1: # if the number isn't 0 and the count is 1, this isn't a group
count = 0
elif count > 1: # if the number isn't 0 and counter is bigger than 1, it is the end of a group
if i - count - 1 >= 0:
out.append([count, l[i - count - 1], l[i]])
else:
out.append([count, "start", l[i]])
count = 0
if count > 1: # there was another group of 0 but no element after the group
if len(l) - count - 1 >= 0:
out.append([count, l[len(l) - count - 1], "end"]) # add a list with only the element before
else:
out.append([count, "start", "end"]) # add a list without element before and after
out[0] = len(out) - 1 # insert number of groups
print(f"{out = }")
# --------- output ---------
# [1, 0, 0, 2, 5, 9, 0, 0, 0, 10] -> out = [2, [2, 1, 2], [3, 9, 10]]
# [0, 1, 0, 0, 2, 5, 9, 0, 0, 0, 10, 0] -> out = [2, [2, 1, 2], [3, 9, 10]]
# [0, 0, 0] -> out = [1, [3, 'start', 'end']]
# [1, 2, 3] -> out = [0]
3条答案
按热度按时间8xiog9wr1#
看起来你可以使用
itertools.groupby
并跟踪前一组零和前一组非零。当你看到一组非零时(只要你看到一些零,就会产生你的结果)。最后你可以把列表的长度放在你的结果前面:5anewei62#
两种解决方案:
输出(Attempt This Online!):
kpbpu0083#
这是我能想到的最好的解决方案,它是
O(n)
。它将在列表上循环1次,并找到所有0的组。