Echo
Echo

Reputation: 1127

Get the first letter of each 2-letter word in python

I have this code:

hand=["TS","AD"]
test=['--23456789TJQKA'.index(a) for a, b in hand]
print (test)

result is :

[10, 14]

How does this snippet work? Is it a built-in function for [a for a, b in list] to get the first letter of each 2-letter word in list in python?

Upvotes: 1

Views: 435

Answers (4)

Craig Burgler
Craig Burgler

Reputation: 1779

The code has something to do with poker or some other card game using a standard 52 card deck. test will be a list of the ordinal "ranks" of a player's hand (the "suit" is not saved). It uses tuple unpacking to put the "rank" of the hand into a and the "suit" into b within the list comprehension.

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113945

First, let's turn the code into a for loop:

hand = ["TS","AD"]
test = []
for a,b in hand:
    test.append('--23456789TJQKA'.index(a))
# note that we didn't use b

print(test)

So what's happening here?
Well, each element in hand is an iterable with two elements. This means that for a,b in hand iterates through each string in hand, assigning the first character to a and the second to b. This is effectively the same as:

for mystr in hand:
    a = mystr[0]
    b = mystr[1]
    # or equivalently, a,b = mystr

The next piece is '--23456789TJQKA'.index(a), which simply returns the index of the first occurrence of a in string '--23456789TJQKA'.

So the output ends up being a list of two numbers - the indices of the first character of each string in hand, namely, 'T' and 'A'

Upvotes: 2

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

Here for a, b in hand part actually unpacks the strings TS and AD. loop variable a and b is assigned to a hand element. Which is like

(a, b) = 'TS'

here a is assigned to T and b is set to S.

After that .index method just looks for a and returns the index of it.

Note: This will not work if hand contains a non-two letter word.

Upvotes: 0

dting
dting

Reputation: 39287

This is a normal list comprehension that is splitting the two letter strings in hand into tuple of letters

for the first element of hand:

a, b in 'TS'
# a == 'T'
# b == 'S'

'--23456789TJQKA'.index('T')
# 10

for the second element of hand:

a, b in 'AD'
# a == 'A'
# b == 'D'

'--23456789TJQKA'.index('A')
# 14

Upvotes: 2

Related Questions