亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用上一個/當前/下一個從列表中獲取唯一值?

如何使用上一個/當前/下一個從列表中獲取唯一值?

白衣非少年 2023-09-26 14:14:19
我已經實現了一個程序,它接受一個列表,并根據前一個、當前和下一個元素返回唯一值。但是,當列表開頭有兩個以上相同元素時,該程序將不起作用。前任:[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“指針” ??偸潜WC有一個值,所以我很困惑為什么諸如此類的輸入不會產生任何結果。previous_itemcurrent_itemprevious_item[0, 0, 0, 1]
查看完整描述

1 回答

?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

你的 while 循環正在測試是否next_item不為 null,意思是不等于0、None[]、{}等...所以一旦該值取 0,循環就會停止。

相反,你可以這樣做:

def test(current):

? ??

? ? iterator = iter(current)

? ? previous_item = next(iterator)

? ? current_item = next(iterator)

? ? next_item = 0

? ??

? ??

? ? while next_item is not None:

? ? ? ??

? ? ? ? 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


查看完整回答
反對 回復 2023-09-26
  • 1 回答
  • 0 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號