Python循环:4个随机数x 6

时间:2017-04-09 22:57:52

标签: python python-2.7 loops for-loop random

我希望有6次4个骰子,6个边(6 x 4d6),我想尝试得到一个循环:

import random

print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6)
print random.randint(1, 6), random.randint(1, 6), random.randint(1, 6), random.randint(1, 6) code here

我尝试这样做:

import random
import tempfile
roll = 0
rzuty = [] #dicethrows
wynik = [] #result


for x in range(6):
    for y in range(4):
        roll = random.randint(1,6)
        rzuty.append(roll)
    rzuty.sort()
    rzuty.pop(0)

    for z in xrange(len(rzuty)):
        tempfile = rzuty

    wynik.append(tempfile)

    print (roll)

我只得到了这个:

1
3
3
4
6
4

Process finished with exit code 0

我尝试了很多东西,但我发现错了。我只是一个初学者。

2 个答案:

答案 0 :(得分:1)

作为一项基本的学习练习,让我们来看看你的代码:

for y in range(4):
    roll = random.randint(1,6)  # Lets say we generated 2,5,3,4
    rzuty.append(roll)
rzuty.sort()

这是一个好的开始,rzuty现在包含4个随机数(已排序):

rzuty = [2,3,4,5]

现在弹出最后一个号码:

rzuty.pop(0)  # Returns 5

现在rzuty包含[2,3,4]。这不对,你不希望pop在那里打电话,它会消除你的一个结果。

现在我们循环rzuty并将tempfile设置为:

for z in xrange(len(rzuty)):
    tempfile = rzuty

这似乎是多余的,可以在没有tempfile = rzuty循环的情况下替换为for

wynik.append(tempfile)
print (roll)

现在wynik == [[2,3,4]]我们打印roll的内容,正如我们从此答案顶部看到的那样4(请注意,这是您在问题中突出显示的问题)

最后一个大问题是你在每次循环后都没有清除rzuty。这意味着您只需更改代码即可保持附加卷,以便print(roll)行更改为print(rzuty)我的最终输出行为:

[2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6]

总结这里是一组有效的代码(Python 2.7):

# removed redundant `import tempfile`
import random

roll = 0
rzuty = [] #dicethrows
wynik = [] #result

for x in range(6):
    # clear rzuty so it doesn't get filled with results over time
    rzuty = []
    for y in range(4):
        roll = random.randint(1, 6)
        rzuty.append(roll)
    rzuty.sort()
    # removed pop discarding results and redundant for loop

    # replaced tempfile with rzuty in append
    wynik.append(rzuty)

    # print rzuty instead of last roll
    print rzuty

示例输出:

[1, 1, 3, 4]
[1, 3, 3, 5]
[1, 2, 5, 6]
[1, 4, 4, 5]
[2, 4, 4, 6]
[1, 1, 5, 6]

答案 1 :(得分:-1)

you only have 2 loops, one nested within another, which only prints out 4*6 = 24 random rolling results.

I'm assuming this only generates 4 dices with 6 sides for 1 time.

to produce 6 times result, simply put your code into another nested loop which loops 6 times.

相关问题