可以在一個迭代函數傳遞,並將其稱之爲next()
從迭代器獲取下一個元素:
self.team_names = iter([...])
self.team1_label.setText(next(self.team_names))
self.team_change(self.team1_label)
def team_change(label):
try:
label.setText(next(self.team_names)) # use next to get the next element
except StopIteration:
# deal with the case when the
# list is exausted.
或者,如果你不能使用迭代器,你可以使用list.pop()
爲零的說法,假設你想在列表的開頭開始,並且其橫置:
self.team1_label.setText(self.team_names.pop(0))
self.team_change(self.team1_label)
def team_change(label):
try:
label.setText(self.team_names.pop(0)) # use list.pop()
except IndexError:
# deal with the case when the
# list is exausted.
正如你所看到的,有兩種方法,你一定要考分別爲StopIteration
錯誤和IndexError
。我不確定你想在列表耗盡時想要發生什麼,所以我把這個細節留給了。
謝謝!和next()相反。像prev()? – BUInvent
@BUInvent不幸的是沒有。當你在迭代器上調用'next()',或者通過'.pop()'從列表中移除一個元素時,你無法恢復。然而,如果你想保存最後一個元素,你可以創建一個實例變量,比如'self.prev',並將它設置爲你上次從列表中刪除的項目。然後,您可以使用它來訪問從列表中刪除的最後一個元素。 –