0

I got the following code.

hand = '6C 7C 8C 9C TC'.split()

so hand is now a list of strings ['6C', '7C', '8C', '9C', 'TC']

then

ranks = ["--23456789TJKA".index(r) for r, s in hand]

ranks is now [6, 7, 8, 9, 10]

The aim is to give card's rank the proper numeric value to allow sorting it: i.e. 'T'->10, 'J'->11, 'Q'-12, 'K'->13 and 'A'->14.

I don't understand why it works!

  • to get an item from a list is list[item]
  • to slice a string is "string"[0]

I do not see it in the ranks list comprehension.

Thank you!

4 Answers4

1

Every element of hand is a string with two characters.

In time of forming ranks, what you are doing is for each element of hand, unpacking the string to two separate variable.

So, in the variable r, you will get

6 7 8 9 T ...

And, in variable s, you will get:

C C C C C ....

Let's see this.

[(r,s) for r, s in hand]

Output:

[('6', 'C'), ('7', 'C'), ('8', 'C'), ('9', 'C'), ('T', 'C')]

And you are forming the list ranks with the index of each of r in the string --23456789TJKA

Let's see how this works:

>>"--23456789TJKA".index('6')
>> 6
>>"--23456789TJKA".index('7')
>> 7
>>"--23456789TJKA".index('8')
>> 8

And so on!

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Check what [(r,s) for r, s in hand] gives you. It's

[('6', 'C'), ('7', 'C'), ('8', 'C'), ('9', 'C'), ('T', 'C')]

This is because you unpack your 2-letter strings into r and s (each string is an iterable).

So when you do index(r), you're searching for the index of the first character only.

Szymon
  • 42,577
  • 16
  • 96
  • 114
0

Strings, like lists, can be iterated through. For example:

>>> for s in 'string':
...     print s
... 
s
t
r
i
n
g

Hence, when you're doing for r, s in hand , it does:

r = '6'
s = 'C' 

For each item (obviously a different value for each item)

TerryA
  • 58,805
  • 11
  • 114
  • 143
0

You're starting with:

>>> hand = ['6C', '7C', '8C', '9C', 'TC']

So consider what happens when you do this:

>>> [(r, s) for r, s in hand]
[('6', 'C'), ('7', 'C'), ('8', 'C'), ('9', 'C'), ('T', 'C')]

The for r, s in hand bit splits each two-character long string into r and s, then puts them together in a tuple. Your code is a little different in that it doesn't put them into a tuple, it just uses the r as the argument to the index function.

101
  • 8,514
  • 6
  • 43
  • 69