【问题标题】:Sort a list of lists within a class Python对类 Python 中的列表列表进行排序
【发布时间】:2012-12-23 17:55:14
【问题描述】:

我已经创建了以下

class uniquePlayers():

    def __init__(self):
        self._item = [ [] for i in range(5) ]
        self.count = 0

    def addPlayer(self, firstInstance, firstName, lastName, Country, long):
        self._item[0].append(firstInstance)
        self._item[1].append(firstName.lower())
        self._item[2].append(lastName.lower())
        self._item[3].append(Country)
        self._item[4].append(long.lower())
        self.count += 1

    def sortByKey(self, index = 4 ):
        self._item[index].sort()

我正在尝试对整个班级进行排序,同时保留其他列表中的所有内容。显然我所做的只是对“长”列表进行排序

【问题讨论】:

    标签: list class python-3.x


    【解决方案1】:

    您应该将属于一起的数据保存在一起。因此,不要有 5 个列表,每个列表都有一个属性,而是有一个包含所有玩家数据的列表:

    def __init__(self):
        self._players = []
    
    def addPlayer(self, firstInstance, firstName, lastName, Country, long):
        player = (firstInstance, firstName.lower(), lastName.lower(), Country, long.lower())
        self._players.append(player)
    
    def sortByKey(self, index=4):
        self._players.sort(key=lambda x: x[index])
    

    您还可以将named tuple 用于玩家数据,以便更轻松地访问它,或者更好地为玩家引入新类型(类)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多