python - 你如何在 python 中将随机值排序为数字顺序?

标签 python random

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 个球需要按数字顺序排列,奖金球需要单独显示。

最佳答案

不使用变量,而是将随机数放入列表中,然后使用 sortedlist.sort 对其进行排序:

>>> import random

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

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

已排序:

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

列表排序:

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

关于python - 你如何在 python 中将随机值排序为数字顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18867788/

相关文章:

python - 编译一个将自动转义或忽略特殊字符的正则表达式

python - 如何从内存中保存webkit页面图片资源?

Python Scrapy没有为每个链接执行scrapy.Request回调函数

arrays - 从数组中随机选择两个不同的项目

python - 在 Python、NumPy 和 R 中创建相同的随机数序列

c# - 生成随机整数时无法包含上限

python - 仅在 Django 启动 ONCE 时执行代码?

python - 在appengine中解析json格式的请求

c - 用C语言编程的整数数组中的唯一随机数

时间:2019-03-08 标签:c++rand()%100