我如何制作这个循环?

时间:2015-05-27 15:47:43

标签: python for-loop

以下是我的计划中此步骤的说明: 创建一个遍历骰子列表的循环。 在循环内部,在骰子列表中的每个值的计数列表中为相应的索引值添加一个。循环完成后,计数列表应该具有骰子列表中每个值出现的次数。继承人我所拥有的:

# Step 1
from random import randint

class Dice(object):
    def __init__(self):
        self.dice = []
        x = 0
        while x < 5:
            self.dice.append(str(randint(1,6)))
            x += 1

hand = Dice() # Creates a Dice object
print hand.dice # Prints the instance variable dice (5 random numbers)


# Step 2
class Dice(object):
    def __init__(self):
        self.dice = []

    def roll(self,how_many):
        for i in range(how_many):
            self.Dice.append(randint(1,6))

hand.roll = ([0,2,3]) # Change the numbers in index positions 0, 2, and 3.
print hand.dice # Prints the instance variable dice (5 random numbers)

#Step 3
def score(self):
    self.counts = [0, 0, 0, 0, 0, 0, 0]
    for i in range(counts):
        index + 1
        print i

1 个答案:

答案 0 :(得分:0)

使用enumerate

>>> lst = [4, 4, 5, 2, 6]
>>> counts = [0] * 7
>>> for i, e in enumerate(lst):
...     counts[e] += 1
...
>>> print counts
[0, 0, 1, 0, 2, 1, 1]
相关问题