【问题标题】:How would I make this Python program with lists/arrays Instead of multiple variables?我将如何使用列表/数组而不是多个变量来制作这个 Python 程序?
【发布时间】:2019-03-04 00:05:18
【问题描述】:

我得到了这个工作,但在制作列表/打电话给他们时很糟糕。任何人都可以将其压缩成列表形式吗? (不是为了家庭作业,已经完成了,只是为了学习机会/练习,所以不要着急。)我假设我的 count 变量可以做成一个列表,并在 for 循环和最终打印期间调用。

这是一个骰子游戏,用于跟踪在掷出 2 个骰子并相加后出现的次数。很容易,我只是在理解列表方面很烂,所以用代码解释会非常有用,我的教科书没有足够地阐述这个话题。第一次在堆栈上发帖,请原谅任何混乱的行话或规则。谢谢!

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")

【问题讨论】:

    标签: python list dice


    【解决方案1】:

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

    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[total-2] = count[total-2] + 1 吗?谢谢!
    • 这是由于代码本身,因为索引计数从 0 开始。对应于索引计数,我们有:0-2,1-3,2-4...10-12
    • 太棒了,我想我明白了。我有点困惑的最后一部分是当你在 print 中调用 x 时。它怎么知道总数是多少?
    • 知道了,第一次设置计数列表时没有发现 X。现在非常有意义,并且非常接近我第一次尝试做的事情。非常感谢!
    【解决方案2】:

    在这种情况下,我会使用字典。 或者特别是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))
    

    【讨论】:

      【解决方案3】:

      创建一个包含 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)))
      

      【讨论】:

        【解决方案4】:

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

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

        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)
        

        【讨论】:

        • 另一方面,底层域是连续的(2..12),所以在这里使用列表肯定没问题。您可以按顺序遍历列表。对于字典,您必须先对其进行排序以确保正确的顺序(啊!)。它们的性能也更好。
        • plus1 用于collections.Counter;这是解决问题的首选方法。
        • @MateenUlhaq 同意——这有点混乱。我更喜欢这样的稀疏数据字典,但是 YMMV :)
        • 有趣的是,我的书还没有涉及到 def 函数,但我已经尝试过它们并将使用它。谢谢!
        【解决方案5】:

        稍微修改了您的代码,我认为如果您使用字典,它将易于使用和理解。

        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")
        

        【讨论】:

        • 谢谢你之前和之后,我还没在字典里,但这是有道理的。你能解释一下 count[total] 和 count[i] 是如何工作的吗?
        • 当然字典有键和值...在计数字典中,只有从 2 到 12 的键......两个骰子的总和总是在 2 到 12 之间。同样的事情发生在 count[i] 部分 iam 只是从 2 循环到 12 并显示输出。
        • 好吧,这是有道理的,最后(我认为)count[I] 怎么知道总数已经滚动了多少次?
        • @JonMH 由于这条线count[total] += 1 每次由两个骰子count 字典生成总数时,保留该特定总数的值......当我试图通过count[i] 我正在获取例如 i=2 的值。 count[2] 将返回键 2 的值
        • 所以我支持整个列表,明白了。非常感谢您的帮助,这正是我所需要的。
        猜你喜欢
        • 2016-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-20
        • 1970-01-01
        相关资源
        最近更新 更多