0

So I have a double problem. I have selectedCards list, which contains 2 elements - card rank and suit, in this format: ['6', 'c']

club = u"\u2663" # Unicode codepoint for club

newList = [club for i in selectedCards if i == 'c' else i]

I want to change 'c' into graphical representation of club, but this expression not working. I tried searching a lot but couldn't find what's wrong. It says: SyntaxError: invalid syntax

Second problem, If I remove else statement, then it works, but it does not output what I want, it looks like this: [u'\u2663'], even thought print(club) outputs ♣.

EDIT: newList = [club if i == 'c' else i for i in selectedCards] is the correct syntax, thanks to xtofl.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
estranged
  • 424
  • 5
  • 16

1 Answers1

0

Probably you are better off with a dict:

symbols = {
  'c': u"\u2663",
  'h': u"....hearts",
  ...
}

newList = [symbols[card] for card in selectedCards]

(or if you want to go functional:

map( symbols.get, selectedCards )

)

As for the 1st problem: cfr https://stackoverflow.com/a/4260304/6610

For the 2nd, printing, problem: python just gives you 'a' list representation; if you want it in string form, this did the trick for me:

print("".join(newList))

(hint: it would be wise to represent you card in a Card class containing all this logic, somewhat like

class Card:
   def __init__(self, rank, suit):
      self.rank = rank
      self.suit = suit

   symbols = {'c': u"\u2663", ...}

   def __str__(self):
      return "".join([self.rank, Card.symbols[self.suit]])

)

Community
  • 1
  • 1
xtofl
  • 40,723
  • 12
  • 105
  • 192
  • I know there are many options to achieve same task, I still wonder why that way does not work. Anyways, your implementation, gives me error `KeyError: 'Q'`, where Q changes depending on rank. I think I need to include condition here to check if it's rank or a suit. – estranged Jul 26 '14 at 11:10
  • For an answer to the list comprehension question, do take a look at http://stackoverflow.com/a/4260304/6610 – xtofl Jul 26 '14 at 11:13
  • xtofl, yep this solved: `newList = [club if i == 'c' else i for i in selectedCards]`! But again I get it like this `['Q', u'\u2663']` which is my 2nd problem. – estranged Jul 26 '14 at 11:17
  • 1
    Wouldn't `__str__` be more appropriate than `__repr__` as this method gives a nice to print string rather than the actual values of the object attributes? see https://docs.python.org/3/reference/datamodel.html#object.__repr__ – A.E. Drew Jul 26 '14 at 12:34