1
import random
import time
print ' Welcome to the lottery number generator'

num_1 = random.randrange(53)+1 #Random numbers
num_2 = random.randrange(53)+1 #Random numbers
num_3 = random.randrange(53)+1 #Random numbers
num_4 = random.randrange(53)+1 #Random numbers
num_5 = random.randrange(53)+1 #Random numbers

Bonus = random.randrange(42)+1 #Bonus ball random numbers

print 'Here are the numbers that have been drawn'
time.sleep(1)
print 'Your first ball'
time.sleep(1)
print num_1
time.sleep(1)
print 'Your second ball'
time.sleep(1)
print num_2
time.sleep(1)
print 'Your third ball'
time.sleep(1)
print num_3
time.sleep(1)
print 'Your fourth ball'
time.sleep(1)
print num_4
time.sleep(1)
print 'Your fifth ball'
time.sleep(1)
print num_5
time.sleep(1)
print 'The bonus ball'
time.sleep(1)
print Bonus

请有人告诉我如何将随机数按数字顺序排列????代码有效,我只需要将它们按数字顺序排列。将有 5 个球需要按数字顺序排列,奖金球需要单独显示。

4

2 回答 2

4

不要使用变量,而是将随机数放在一个列表中,然后使用sortedor对其进行排序list.sort

>>> import random

使用 alist comprehension创建一个包含随机项的列表:

>>> nums = [random.randrange(53)+1 for _ in xrange(5)]
>>> nums
[51, 49, 23, 27, 29]

sorted

>>> sorted(nums)     #return a new sorted list, original list is not affected
[23, 27, 29, 49, 51]

list.sort

>>> nums.sort()      #sort the list in-place
>>> nums
[23, 27, 29, 49, 51]

代码:

pos = ['first', 'second', 'third', 'fourth', 'fifth']
for ball, ind in zip(sorted(nums), pos):
    time.sleep(1)
    print 'Your {} ball'.format(ind)
    time.sleep(1)
    print ball
于 2013-09-18T08:55:12.357 回答
0

首先,您应该列出一个数字,而不是创建几个不同的变量。然后你可以只使用list.sort()对数字进行排序。

numlist = []
for i in range(0, 5):
    numlist.append(random.randrange(53)+1)
numlist.append(random.randrange(42)+1)

numlist.sort()
于 2013-09-18T09:01:53.590 回答