我已经实现了一个程序,它接受一个列表,并根据前一个、当前和下一个元素返回唯一值。
但是,当列表开头有两个以上相同元素时,该程序将不起作用。
前任:[0, 0, 0, 1]
这是代码,后面是机制的描述。
def test(current):
iterator = iter(current)
previous_item = next(iterator)
current_item = next(iterator)
next_item = True
while next_item:
try:
next_item = next(iterator)
except StopIteration:
next_item = None
if previous_item == current_item:
current_item = next_item
else:
yield previous_item
previous_item = current_item
current_item = next_item
if previous_item:
yield previous_item
if __name__ == "__main__":
l = [0, 0, 1, 2]
for u in test(l):
print(u)
next_item如果是,则循环终止None。我只产生一个previous_itemif previous_itemis not equal to current_item。如果不等于,我也只移动previous_item“指针” 。总是保证有一个值,所以我很困惑为什么诸如此类的输入不会产生任何结果。previous_itemcurrent_itemprevious_item[0, 0, 0, 1]
一只名叫tom的猫
相关分类