Python 我怎么做这个循环?

Python 我怎么做这个循环?,python,for-loop,Python,For Loop,以下是我的程序中这一步的说明: 创建一个遍历骰子列表的循环。 在循环内部,为骰子列表中的每个值向计数列表中的相应索引值添加一个。循环完成后,计数列表应具有骰子列表中每个值出现的次数。以下是我所拥有的: # Step 1 from random import randint class Dice(object): def __init__(self): self.dice = [] x = 0 while x < 5:

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

# 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
从随机导入randint
类骰子(对象):
定义初始化(自):
self.dice=[]
x=0
当x<5时:
self.dice.append(str(randint(1,6)))
x+=1
hand=Dice()#创建骰子对象
print hand.dice#打印实例变量dice(5个随机数)
#步骤2
类骰子(对象):
定义初始化(自):
self.dice=[]
def辊(自身,数量):
对于范围内的i(有多少个):
self.Dice.append(randint(1,6))
hand.roll=([0,2,3])#更改索引位置0、2和3的数字。
print hand.dice#打印实例变量dice(5个随机数)
#步骤3
def分数(自我):
self.counts=[0,0,0,0,0,0,0]
对于范围内的i(计数):
索引+1
打印i
使用:


为什么类骰子声明两次?这甚至不应该在python中运行。只是一个一般性的评论。在步骤1的
\uuuu init\uuuuu()
中,执行
self.dice.append()
的一种更为类似于
的方法是在xrange(6):self.dice.append(str(randint(1,6))
(当然,将其拆分到
后面的第二行:
)。这样就不需要初始化和递增计数器变量(
x
)。您实际上是在构建直方图吗?
>>> 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]