抓住列表中的下一个项目?

时间:2017-05-31 02:05:30

标签: python arrays list pyqt pyqt5

好的,我想让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

2 个答案:

答案 0 :(得分: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。当列表用尽时,我不确定你想要发生什么,所以我把这个细节留给了。

答案 1 :(得分: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])

只是想我会让每个人都知道。

相关问题