2017-08-09 22 views
2

我的代码大部分工作完美,唯一我无法弄清楚是三种。如果出现三个相同的数字,则它们会相加得到分数。这是我现在拥有的那部分代码。我必须在Python中制作一个Yahtzee游戏。其他的工作,但我不能得到三种工作

def threeOfOne(dicelst): 
    total = 0 
    for die in dicelst: 
     if dicelst[0] == dicelst[1:3]: 
      total += die 
     elif dicelst[1] == dicelst[2:5]: 
      total += die 
     else: 
      total = 0 
     return total 

我觉得我缺少一些非常简单的东西,但我不能得到它的工作它总是显示零。

+0

您正在比较单个值与列表! – ti7

+0

https://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical – Lafexlos

回答

0

在你的函数中,你正在检查单个值是否等于一个列表!

>>> dicelst = [1,3,5,4,2] 
>>> dicelst[0] 
1 
>>> dicelst[1:3] 
[3, 5] 

尝试检查每个count列表

def threeOfOne(dicelst): 
    for die in dicelst: 
     if dicelst.count(die) >= 3: # only if there are at least three matches 
      return die * dicelst.count(die) 
    return 0 

这里死了,是我相信的表情解决您的问题

def threeOfOne(dicelst): 
    return sum(x for x in dicelst if dicelst.count(x) >= 3) 

由此,在dicelst其中出现的所有值至少三次

  • (x for x in y)它迭代Ÿ
  • dicelst.count(x)数乘以x的数字出现在dicelst
  • sum(iterable)发电机表达式添加在包含列表一切(或其他可迭代)

如果您需要整整三的种类,只需检查计数== 3

相关问题