【问题标题】:How to turn this code into a list comprehension如何将此代码转换为列表理解
【发布时间】:2016-01-05 11:20:21
【问题描述】:

简单的问题,我正在努力熟练掌握 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]

您可以看到正在工作的 for 循环(返回 14)和我在 LC 实现中的尝试。它返回一个列表 [4, 10]

如何让它返回该列表中元素的总和?

【问题讨论】:

  • This 可能会有所帮助

标签: python list-comprehension


【解决方案1】:
print sum(VALUES[card[-1]] for card in hand if card[-1] in VALUES)

【讨论】:

  • 您不需要在列表中缓冲理解; sum(VALUES[card[-1]] for ...) 就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 2017-11-23
  • 2020-04-25
相关资源
最近更新 更多