python 3.x - sorting a list of objects_python_3 -


how can sort "cardslistobj" suit , rank?
i've done "print (cardslistobj.sort (key = card.getrank))" , didn't work, have "none".
did on code quite same (in opinion newbie) , worked. (that code 300 lines that's why didn't post it, here)

class card :      def __init__ (self, rank, suit) :          self.rank = rank # cards numbers         self.suit = suit # cards characters diamonds, clubs, hearts, spades      def getrank (self):          return self.rank      def getsuit (self):          return self.suit  def main():      cards = open (input ("file? "))     cardslistobj = []      in cards:          cardobj = card (i.split () [0], i.split () [1])         cardslistobj.append (cardobj) 

input file txt file number , name of cards in each line separated space.

thanks in advance

if want sort cards, can create function this:

from operator import attrgetter  def sort_cards(cards): #cards list containing 'cards' objects     """function sorting cards"""      return sorted(cards, key=attrgetter('suit', 'rank'))  deck = [     cards(3, 'diamonds'),     cards(7, 'clubs'),     cards(5, 'hearts'),     cards(8, 'diamonds'),     cards(4, 'spades'),     cards(10, 'clubs') ] print(sort_cards(deck)) 

output (you should define method __repr__)

['7 of clubs', '10 of clubs', '3 of diamonds', '8 of diamonds', '5 of hearts', '4 of spades'] 

nb: in example, __repr__ that:

class card:  [...]  def __repr__(self):     return '%d of %s' % (self.rank, self.suit) 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -