在Python中遍历对象实例的最佳方法是什么?

时间:2018-10-31 03:27:34

标签: python

我对Python还是很陌生,所以请允许我。我创建了一个名为team的类,它具有4个属性(city, teamname, wins, losses)。我已经创建了team (team_1, team_2, team_3, team_4, team_5)的5个实例,并且已经初始化了它们的属性。请参见下面的代码。我正在寻找一种遍历实例并产生输出的列表,该输出按升序排列列出球队。我不确定执行此操作的最佳方法是从实例中以某种方式创建列表或字典,或者是否存在更有效的方法来遍历实例。再次,我对Python感到非常环保,非常感谢我能获得的任何帮助。预先感谢您的宝贵时间!

class team:

    def __init__(self, city, teamname, wins, losses):
        self.city = city
        self.teamname = teamname
        self.wins = wins
        self.losses = losses

team_1 = team('Boston','Red Sox', 162, 0)
team_2 = team('New York', 'Yankees', 0, 162)
team_3 = team('Tampa Bay', 'Rays', 80, 82)
team_4 = team('Toronto', 'Blue Jays', 82, 80)
team_5 = team('Baltimore', 'Orioles', 1, 161) 

4 个答案:

答案 0 :(得分:1)

Python内置了teams = [] teams.append(team('Boston','Red Sox', 162, 0)) teams.append(team('New York', 'Yankees', 0, 162)) teams.append(team('Tampa Bay', 'Rays', 80, 82)) teams.append(team('Toronto', 'Blue Jays', 82, 80)) teams.append(team('Baltimore', 'Orioles', 1, 161)) 排序功能 https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

您可以将其传递给密钥。所以我们开始:

sorted

答案 1 :(得分:1)

正如许多评论中提到的那样,创建列表并进行遍历是最简单的方法。

team_list = []
team_list.append(team('Boston','Red Sox', 162, 0))
team_list.append(team('Boston','Red Sox', 162, 0))
team_list.append(team('New York', 'Yankees', 0, 162))
team_list.append(team('Tampa Bay', 'Rays', 80, 82))
team_list.append(team('Toronto', 'Blue Jays', 82, 80))
team_list.append(team('Baltimore', 'Orioles', 1, 161))

# For sorting the teams
sorted_team = sorted(team_list, key=lambda team: team.wins)
print([team.city for team in sorted_team])

答案 2 :(得分:1)

您可以在这样的类中定义运算符<(小于):

class Team:
    def __init__(self, city, teamname, wins, losses):
        self.city = city
        self.teamname = teamname
        self.wins = wins
        self.losses = losses

    def __lt__(self, other):
        return self.wins < other.wins

    def __repr__(self):
        return self.teamname # or what you want to show

这样,python知道如何对此类中的对象列表进行排序。

sorted_list = sorted([team_1, team_2, team_3, team_4, team_5])

通过定义表示形式运算符,python也知道在这些对象之一上调用print函数时显示的内容。

答案 3 :(得分:0)

创建一个空列表,然后将每个新的团队对象Function ShortestString(ByVal array1 As Range) Dim nRows As Integer Dim i As Integer Dim cell As String Dim cellLength As Integer Dim string1 As String nRows = array1.Rows.Count cellLength = 100 cell = array1.Cells(i, 1).Value For i = 1 To nRows If cellLength > Len(cell) Then cellLength = Len(cell) string1 = cell End If Next i ShortestString = string1 End Function 移至列表中:

append()