我如何使用 lists/arrays 而不是多个变量来制作这个 Python 程序?

How would I make this Python program with lists/arrays Instead of multiple variables?

我成功了,但是 lists/calling 制作起来很糟糕。谁能将其压缩成列表形式? (不是为了作业,已经完成了,只是为了学习opportunity/practice,所以不用着急。)我假设我的计数变量可以做成一个列表,并在for循环和最后的打印中调用。

这是一个骰子游戏,它跟踪在抛出 2 个骰子并将其相加后出现数字的次数。很简单,我只是不擅长理解列表,所以用代码进行解释会非常合适,我的教科书对这个主题的阐述不够。首先 post 在堆栈上,请原谅任何混乱的行话或规则。谢谢!

import random

count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
count10 = 0
count11 = 0
count12 = 0

rolls = int(input("How many times would you like to roll? "))



for i in range(rolls):

    die1 = random.randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = random.randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)


    if total == 2:
        count2 += 1
    elif total == 3:
        count3 += 1
    elif total == 4:
        count4 += 1
    elif total == 5:
        count5 += 1
    elif total == 6:
        count6 += 1
    elif total == 7:
        count7 += 1
    elif total == 8:
        count8 += 1
    elif total == 9:
        count9 += 1
    elif total == 10:
        count10 += 1
    elif total == 11:
        count11 += 1
    elif total == 12:
        count12 += 1


print("You rolled " + str(count2) + " 2's")
print("You Rolled " + str(count3) + " 3's")
print("You Rolled " + str(count4) + " 4's")
print("You Rolled " + str(count5) + " 5's")
print("You Rolled " + str(count6) + " 6's")
print("You Rolled " + str(count7) + " 7's")
print("You Rolled " + str(count8) + " 8's")
print("You Rolled " + str(count9) + " 9's")
print("You Rolled " + str(count10) + " 10's")
print("You Rolled " + str(count11) + " 11's")
print("You Rolled " + str(count12) + " 12's")

创建一个包含 11 个零的列表:

counts = [0] * (12 - 2 + 1)

增加计数:

counts[total - 2] += 1

现在一起:

import random

def roll_dice():
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total = die1 + die2

    print(f"Roll number 1 = {die1}")
    print(f"Roll number 2 = {die2}")
    print(total)

    return total

min_count = 2
counts = [0] * (12 - min_count + 1)
rolls = int(input("How many times would you like to roll? "))

for i in range(rolls):
    total = roll_dice()
    counts[total - min_count] += 1

print('\n'.join(f"You rolled {x} {i + min_count}'s"
    for i, x in enumerate(counts)))

稍微修改了你的代码,我想如果你使用字典,它会更容易使用和理解。

import random

# count2 = 0
# count3 = 0
# count4 = 0
# count5 = 0
# count6 = 0
# count7 = 0
# count8 = 0
# count9 = 0
# count10 = 0
# count11 = 0
# count12 = 0

count = {i: 0 for i in range(2,13)}

rolls = int(input("How many times would you like to roll? "))



for i in range(rolls):

    die1 = random.randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = random.randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)



    # if total == 2:
    #     count2 += 1
    # elif total == 3:
    #     count3 += 1
    # elif total == 4:
    #     count4 += 1
    # elif total == 5:
    #     count5 += 1
    # elif total == 6:
    #     count6 += 1
    # elif total == 7:
    #     count7 += 1
    # elif total == 8:
    #     count8 += 1
    # elif total == 9:
    #     count9 += 1
    # elif total == 10:
    #     count10 += 1
    # elif total == 11:
    #     count11 += 1
    # elif total == 12:
    #     count12 += 1

    count[total] += 1
# print("You rolled " + str(count2) + " 2's")
# print("You Rolled " + str(count3) + " 3's")
# print("You Rolled " + str(count4) + " 4's")
# print("You Rolled " + str(count5) + " 5's")
# print("You Rolled " + str(count6) + " 6's")
# print("You Rolled " + str(count7) + " 7's")
# print("You Rolled " + str(count8) + " 8's")
# print("You Rolled " + str(count9) + " 9's")
# print("You Rolled " + str(count10) + " 10's")
# print("You Rolled " + str(count11) + " 11's")
# print("You Rolled " + str(count12) + " 12's")

for i in range(2,13):    
    print("You rolled " + str(count[i]) + " "+i+"'s")

我只是稍微编辑了你的代码:

from random import randint
rolls = int(input("How many times would you like to roll? "))
count = [0 for x in range(11)] #since 2 to 12 is 11 items
for i in range(rolls):
    die1 = randint(1, 6)
    print("Roll number 1 = " + str(die1))
    die2 = randint(1, 6)
    print("Roll number 2 = " + str(die2))
    total = die1 + die2
    print(total)
    #total will start with 2, while count index with 0, so
    #minus 2 to make it match the index
    count[total-2] = count[total-2] +1
for x in range(11):
    print("You rolled " + str(count[x]) + " " + str(x+2)+ "'s")

您可以在此处使用列表或字典。我倾向于字典,我认为它最能代表您在这里要使用的那种稀疏数据结构(count 列表的第一个元素是什么?它始终为零,但不应该真的是什么都没有吗?零被掷出一次更有意义,还是根本不能掷出更有意义?)

该词典最好简单地定义为:

counts = {}

# You can also generalize your rolling 2d6!
def roll_dice(num_dice, sides):
    total = 0
    for _ range(num_dice):
        dieroll = random.randint(1, sides)
        total += dieroll
    return total

for _ in range(rolls):
    roll = roll_dice(2, 6)
    counts.setdefault(roll, 0) += 1  # this is using dict.setdefault

for roll, count in sorted(counts.items()):
    print("You rolled {} {}s".format(count, roll))

您也可以使用 collections.Counter 来完成此操作。

rolls = [roll_dice(2, 6) for _ in num_rolls]
# this will generate a list like [3, 12, 6, 5, 9, 9, 7, ...],
# just a flat list of rolls.

result = collections.Counter(rolls)

在这种情况下我会使用字典。 或者具体来说 defaultdict.

import random
from collections import defaultdict

roll_scores = defaultdict(int)
rolls = 10

for _ in range(rolls):
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    total = die1 + die2

    print("Roll 1: ", die1)
    print("Roll 2:", die2)
    print("Total:", total)

    roll_scores[total] +=1

for k in roll_scores:
    print("You rolled {} {}'s".format(roll_scores[k], k))

但是如果你想使用列表,这个概念几乎是相同的。 将 roll_scores 更改为 13 项列表(0 到 12):

roll_scores = [0]*13

并更改末尾的打印:

for i in range(len(roll_scores)):
    print("You rolled {} {}'s".format(roll_scores[i], i))