[英]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? 它是[用于列表中的a,b的a]的内置函数,以获取python中列表中每个2个字母的单词的第一个字母吗?
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: 首先,让我们将代码转换为for循环:
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. 好吧, hand
每个元素都是两个元素的迭代。 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
. 这意味着, for a,b in hand
遍历每个串hand
,分配第一个字符到a
和第二至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'
. 下一块是'--23456789TJQKA'.index(a)
,其简单地返回的第一次出现的索引a
字符串'--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'
因此,输出最终是两个数字的列表- hand
每个字符串的第一个字符的索引,即'T'
和'A'
Here for a, b in hand
part actually unpacks the strings TS
and AD
. 在这里, for a, b in hand
部分实际上解压缩了字符串TS
和AD
。 loop variable a
and b
is assigned to a hand
element. 循环变量a
和b
被分配给hand
元素。 Which is like 就像
(a, b) = 'TS'
here a is assigned to T
and b is set to S
. 在这里,a分配给T
,b设置为S
After that .index
method just looks for a
and returns the index of it. 之后,该.index
方法仅查找a
并返回其索引。
Note: This will not work if hand
contains a non-two letter word. 注意:如果hand
包含非两个字母的单词,此功能将无效。
The code has something to do with poker or some other card game using a standard 52 card deck. 该代码与使用标准52卡座的扑克牌或其他纸牌游戏有关。 test
will be a list of the ordinal "ranks" of a player's hand (the "suit" is not saved). test
将是玩家手的顺序“等级”列表(“套装”未保存)。 It uses tuple unpacking to put the "rank" of the hand into a
and the "suit" into b
within the list comprehension. 它使用元组拆包在列表推导中将手的“等级”放入a
,将“西装”放入b
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.