2017-05-31 29 views
0

好的,我想讓team_change成爲一個函數,將team1_label的文本設置爲列表中的下一個team_name(在本例中爲self.team_names [1])。有沒有實用的解決方案?抓取列表中的下一個項目?

self.team1_label.setText(self.team_names[0]) 
self.team_change(self.team1_label) 

def team_change(label): 
    label.setText(self.team_names.nextelement) #this is what I need help on 

回答

1

可以在一個迭代函數傳遞,並將其稱之爲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。我不確定你想在列表耗盡時想要發生什麼,所以我把這個細節留給了。

+0

謝謝!和next()相反。像prev()? – BUInvent

+0

@BUInvent不幸的是沒有。當你在迭代器上調用'next()',或者通過'.pop()'從列表中移除一個元素時,你無法恢復。然而,如果你想保存最後一個元素,你可以創建一個實例變量,比如'self.prev',並將它設置爲你上次從列表中刪除的項目。然後,您可以使用它來訪問從列表中刪除的最後一個元素。 –

0

好吧,我想我發現這樣做的一個好辦法:

self.team1_label.setText(self.team_names[0]) 
self.team_change(self.team1_label) 

def team_change(label): 
    label.setText(self.team_names[self.team_names.index(label.text())+1]) 

只是覺得應該讓大家知道。

相關問題