0

I am trying to find out if there is an way to see how many of an object (count) from one list is in another list.

I have a class Card.

class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

    def getNumber(self, card):
        return card.number

I have a class Deck which contains a list of Cards.

class Deck(object):
    def __init__(self):
        self.cards = []
        for i in range(11):
            for j in range(i):
                self.cards.append(Card(i))

I want to see if a I can get the count of a Card in the Deck.

deck = Deck()
The deck contains 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 

cards = [Card(6), Card(5), Card(3)]
The cards are 6 5 3

I want to know how many 6's, 5's and 3's there are in the deck.

Anthony
  • 23
  • 2
  • https://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string –  Jan 30 '18 at 05:14
  • I tried this and it works for how many 6's, 5's and 3's there are in the deck. for card in cards: print(deck.cards.count(card)) The result is: 6 5 3 – Anthony Jan 30 '18 at 05:20
  • Thanks for all of the answers – Anthony Jan 30 '18 at 05:27

3 Answers3

2

To tally an individual card, use list.count():

for card in cards:
    print(deck.cards.count(card))

To tally them all, use collections.Counter():

>>> from collections import Counter
>>> Counter(deck.cards)
Counter({Card(10): 10, Card(9): 9, Card(8): 8, Card(7): 7,
         Card(6): 6, Card(5): 5, Card(4): 4, Card(3): 3,
         Card(2): 2, Card(1): 1})

For the counter to work, you'll need to make minor modifications to your Card class by adding __hash__() and __repr__() methods:

class Card(object):
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == other.number

    def __hash__(self):
        return hash(self.number)

    def getNumber(self, card):
        return card.number

    def __repr__(self):
        return 'Card(%r)' % self.number
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
0

You can try:

print "Count for 6's: ", ListName.count(6)

Similarly for 5 and 3:

print "Count for 5's: ", ListName.count(5)
print "Count for 3's: ", ListName.count(3)
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
0

I think you can try in this way

>>> from collections import Counter
>>> deck1
['1', '2', '2', '3', '3', '3', '4', '4', '4', '4', '5', '5', '5', '5', '5', 
'6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '8', '8', 
'8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', 
'10', '10', '10', '10', '10', '10', '10', '10', '10', '10']
>>> Counter(deck1)
Counter({'10': 10, '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3, 
'2': 2, '1': 1})
Ashok Kumar Jayaraman
  • 2,887
  • 2
  • 32
  • 40