简体   繁体   中英

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?

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

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'

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM