版本一 :random.randint()版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
from time import sleep


# 双色球 红1~33  蓝1~16
# 大乐透 红1~35  蓝1~12

def SSQ(try_nums):
    """双色球随机选号"""
    red_num_li = []
    blue_num_li = []
    for i in range(try_nums):
        red_num_li.clear()
        blue_num_li.clear()
        while len(red_num_li) <= 5:
            temp_r_num = randint(1, 33)
            if temp_r_num not in red_num_li:
                red_num_li.append(temp_r_num)

        temp_b_num = randint(1, 16)
        blue_num_li.append(temp_b_num)
        red_num_li.sort()  # 从小到大排序
        format_li(red_num_li, blue_num_li)


def DLT(try_nums):
    """大乐透随机选号"""
    red_num_li = []
    blue_num_li = []
    for i in range(try_nums):
        red_num_li.clear()
        blue_num_li.clear()
        while len(red_num_li) <= 4:
            temp_r_num = randint(1, 35)
            if temp_r_num not in red_num_li:
                red_num_li.append(temp_r_num)

        while len(blue_num_li) <= 1:
            temp_b_num = randint(1, 12)
            if temp_b_num not in blue_num_li:
                blue_num_li.append(temp_b_num)

        red_num_li.sort()
        blue_num_li.sort()
        format_li(red_num_li, blue_num_li, 'dlt')


def format_li(red_num_li, blue_num_li, type='ssq'):
    """格式化列表,美观显示列表"""
    # li = [2, 7, 8, 12, 20, 23]
    for i in red_num_li:
        idx = red_num_li.index(i)
        if i < 10:
            red_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            red_num_li.insert(idx, '0{}'.format(i))

    for i in blue_num_li:
        idx = blue_num_li.index(i)
        if i < 10:
            blue_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            blue_num_li.insert(idx, '0{}'.format(i))

    # print(red_num_li)
    # print(blue_num_li)
    if type == 'ssq':
        print('{},{},{},{},{},{} — {}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3], red_num_li[4],
                                              red_num_li[5], blue_num_li[0]))
    else:
        print('{},{},{},{},{} — {},{}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3], red_num_li[4],
                                              blue_num_li[0], blue_num_li[1]))




def run():
    while True:
        print('\n[随机选号器]选项:1双色球  2大乐透  3退出')
        type = input('请输入选项:')
        if type not in ['1', '2', '3']:
            print('选项有误,请重新输入!')
            continue
        if type == '3':
            print('再见!')
            sleep(1)
            break

        try:
            try_nums = int(input('请输入随机次数:'))
            if try_nums <= 0:
                try_nums = 1
        except:
            try_nums = 1

        if type == '1':
            SSQ(try_nums)
        elif type == '2':
            DLT(try_nums)



if __name__ == '__main__':
    # li1 = [2, 7, 8, 12, 20, 23]
    # li2 = [8]
    # format_li(li1, li2)
    # SSQ(10)
    # DLT(10)
    run()
    pass


  感觉版本一选的号码,不是“真随机”,也可能彩票开奖中心的摇号设备,不是真随机。网上查资料发现了random.sample(population, k)函数,可以简化版本一,参考链接如下:
random — 生成伪随机数
random.sample(population, k)介绍
  从整体样本中无重复的随机抽样,感觉就是为彩票抽奖设计的。

版本二:random.sample(population, k)版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint, sample
from time import sleep


# 双色球 红1~33  蓝1~16
# 大乐透 红1~35  蓝1~12

def SSQ(try_nums):
    """双色球随机选号"""
    for i in range(try_nums):
        red_num_li = sample(range(1, 34), 6)
        blue_num_li = sample(range(1, 17), 1)
        red_num_li.sort()  # 从小到大排序
        format_li(red_num_li, blue_num_li)


def DLT(try_nums):
    """大乐透随机选号"""
    for i in range(try_nums):
        red_num_li = sample(range(1, 36), 5)
        blue_num_li = sample(range(1, 13), 2)
        red_num_li.sort()
        blue_num_li.sort()
        format_li(red_num_li, blue_num_li, 'dlt')


def format_li(red_num_li, blue_num_li, type='ssq'):
    """格式化列表,美观显示列表"""
    # li = [2, 7, 8, 12, 20, 23]
    for i in red_num_li:
        idx = red_num_li.index(i)
        if i < 10:
            red_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            red_num_li.insert(idx, '0{}'.format(i))

    for i in blue_num_li:
        idx = blue_num_li.index(i)
        if i < 10:
            blue_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            blue_num_li.insert(idx, '0{}'.format(i))

    # print(red_num_li)
    # print(blue_num_li)
    if type == 'ssq':
        print('{},{},{},{},{},{} — {}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3], red_num_li[4],
                                              red_num_li[5], blue_num_li[0]))
    else:
        print('{},{},{},{},{} — {},{}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3], red_num_li[4],
                                              blue_num_li[0], blue_num_li[1]))


def run():
    while True:
        print('\n[随机选号器]选项:1双色球  2大乐透  3退出')
        type = input('请输入选项:')
        if type not in ['1', '2', '3']:
            print('选项有误,请重新输入!')
            continue
        if type == '3':
            print('再见!')
            sleep(1)
            break

        try:
            try_nums = int(input('请输入随机次数:'))
            if try_nums <= 0:
                try_nums = 1
        except:
            try_nums = 1

        if type == '1':
            SSQ(try_nums)
        elif type == '2':
            DLT(try_nums)


if __name__ == '__main__':
    # li1 = [2, 7, 8, 12, 20, 23]
    # li2 = [8]
    # format_li(li1, li2)
    # SSQ(10)
    # DLT(10)
    run()
    pass

  最后附上两个版本代码打包生成的exe,双击就可以运行。有中奖的朋友留个言,也让我高兴一下。
链接:百度云链接地址
提取码:4e22

版本三:保存随机选号数据到Excel

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint, sample
from time import sleep
from lottery.sui_ji_xuan_hao.demo1 import save_data_to_excel


# 双色球 红1~33  蓝1~16
# 大乐透 红1~35  蓝1~12
# 在随机选号的基础上,添加保存选号数据到Excel中,并输出

def SSQ(try_nums):
    """双色球随机选号"""
    dict_li = []
    for i in range(try_nums):
        red_num_li = sample(range(1, 34), 6)
        blue_num_li = sample(range(1, 17), 1)
        red_num_li.sort()  # 从小到大排序
        nums = format_li(red_num_li, blue_num_li)
        # 组织字典数据,准备写入数据库
        dict_li.append({'随机选号数据': nums})
    save_data_to_excel('双色球', dict_li)


def DLT(try_nums):
    """大乐透随机选号"""
    dict_li = []
    for i in range(try_nums):
        red_num_li = sample(range(1, 36), 5)
        blue_num_li = sample(range(1, 13), 2)
        red_num_li.sort()
        blue_num_li.sort()
        nums = format_li(red_num_li, blue_num_li, 'dlt')
        # 组织字典数据,准备写入数据库
        dict_li.append({'随机选号数据': nums})
    save_data_to_excel('大乐透', dict_li)


def format_li(red_num_li, blue_num_li, type='ssq'):
    """格式化列表,美观显示列表"""
    # li = [2, 7, 8, 12, 20, 23]
    for i in red_num_li:
        idx = red_num_li.index(i)
        if i < 10:
            red_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            red_num_li.insert(idx, '0{}'.format(i))

    for i in blue_num_li:
        idx = blue_num_li.index(i)
        if i < 10:
            blue_num_li.remove(i)  # 替换一位数的元素为两位数(前面加0)
            blue_num_li.insert(idx, '0{}'.format(i))

    # print(red_num_li)
    # print(blue_num_li)
    if type == 'ssq':
        nums = '{},{},{},{},{},{} — {}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3],
                                               red_num_li[4],
                                               red_num_li[5], blue_num_li[0])
    else:
        nums = '{},{},{},{},{} — {},{}'.format(red_num_li[0], red_num_li[1], red_num_li[2], red_num_li[3],
                                               red_num_li[4],
                                               blue_num_li[0], blue_num_li[1])

    print(nums)
    return nums


def run():
    while True:
        print('\n[随机选号器]选项:1双色球  2大乐透  3退出')
        type = input('请输入选项:')
        if type not in ['1', '2', '3']:
            print('选项有误,请重新输入!')
            continue
        if type == '3':
            print('再见!')
            sleep(1)
            break

        try:
            try_nums = int(input('请输入随机次数:'))
            if try_nums <= 0:
                try_nums = 1
        except:
            try_nums = 1

        if type == '1':
            SSQ(try_nums)
        elif type == '2':
            DLT(try_nums)


if __name__ == '__main__':
    # li1 = [2, 7, 8, 12, 20, 23]
    # li2 = [8]
    # format_li(li1, li2)
    # SSQ(10)
    # DLT(10)
    run()
    pass

save_data_to_excel() 方法代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import time


def save_data_to_excel(type, dict_li):
    """把数据保存到Excel中"""
    try:
        print('正在保存数据...')
        writer = pd.ExcelWriter('{}{}.xlsx'.format(type, time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())))
        df1 = pd.DataFrame(data=dict_li)  # 在同一列不同行写入数据
        df1.to_excel(writer, sheet_name='表1', )
        writer.close()
        print('保存数据已完成')
    except Exception as e:
        print('保存数据失败,错误信息:{}'.format(e))


if __name__ == '__main__':
    # 用于测试把数据存储到Excel中
    dict_li = [{'col1': '0,1,2,3,4,5-6'}, {'col1': '0,1,2,3,4,5-7'}, {'col1': '0,1,2,3,4,5-8'}]
    save_data_to_excel('双色球', dict_li)
    pass

版本三打包的exe文件,双击即可运行。
链接:百度云链接地址
提取码:fobj

参考资料

Python下探究随机数的产生原理和算法
Python 使用pandas操作Excel

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐