简单的问题,我正在尝试熟练使用LC并为项目编写“二十一点”。以下是代码示例:
# define globals for cards
SUITS = ['C', 'S', 'H', 'D']
RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
VALUES = {'A':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':10, 'Q':10, 'K':10}
hand = ['C4','HK'] #4 of spades and the king of hearts should total 14
total = 0
for card in hand:
if card[-1] in VALUES:
total += VALUES[card[-1]]
print total
total = 0
print [total+VALUES[card[-1]] for card in hand if card[-1] in VALUES]
你可以看到working for循环(返回14)和我对LC实现的尝试。它返回一个列表[4,10]
如何让它返回该列表中元素的总和?
答案 0 :(得分:5)
print sum(VALUES[card[-1]] for card in hand if card[-1] in VALUES)