【发布时间】:2020-05-10 15:15:22
【问题描述】:
当我有这个功能时,我想打印列表的最后 10 个值。但是,我不知道这样做很热。
import random
roll_list = [0]*13
#holds the number of times each number was rolled
# has 13 spots (0 - 12). roll_list[1] is how many times
# a 1 was rolled.
num_rolls = 100 # number of times to roll the dice
# initialize the roll_list[] so it has the correct number of spots
def init_list():
for _ in range(num_rolls):
Newdice = roll_dice()
update_list(Newdice)
# use a for loop and list.append( x ) to fill the roll_list with 13 zeros
# returns the sum of the two dice that were rolled
def roll_dice():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
Newdice = dice1 + dice2
return Newdice
# roll 2 standard die and return the sum (should be from 2 to 12)
# random.randint() will be helpful here
# change this line so it returns the correct sum
def update_list(Newdice):
roll_list[Newdice] += 1
# add 1 to the list location associated with the total roll value
# example: if the total of the roll is 7, then add 1 to roll_list[7]
def print_histgram():
for num in range(len(roll_list)):
count = roll_list[num]
print("{:2} {}".format(num, "*" * count))
# for 100% create and print a histogram of the results of all
# of the dice rolls
# main program
if __name__ == "__main__":
init_list()
print_histgram()
# make a for loop that calls both roll_dice() and update_list() to roll the dice
# and update the list based on that result. The loop should repeat the number
# of times the die are to be rolled.
# for a 90%, print the final list here
# for a 100% complete print_histogram() and call it here
我的目标和理想的输出
[0, 0, 4, 2, 7, 12, 12, 22, 12, 13, 9, 3, 4]
0:
1:
2: ****
3: **
4: *******
5: ************
6: ************
7: **********************
8: ************
9: *************
10: *********
11: ***
12: ****
我用的时候
print(roll_list[-10:])
The output is
[0,0,0,0,0,0,0,0,0,0]
这段代码有什么问题?我可以使用什么代码?请教我如何解决这个功能。 我搜索了很多,但搜索代码与我的功能不匹配。
【问题讨论】: