"""
Author: Seven_0507
Date:2019-05-19
"""
Day04主要重新学习总结Python字符串及数据结构知识点!
def main():
str1 = 'hello, world!'
print(str1)
# 通过len函数计算字符串的长度
print("len(str1) =", len(str1))
# 获得字符串首字母大写的拷贝
print("str1首字母大写 =", str1.capitalize())
# 获得字符串变大写后的拷贝
print("str1变大写 =", str1.upper())
# 从字符串中查找子串所在位置
print("str1.find('or') =", str1.find('or'))
print("str1.find('shit') =", str1.find('shit'))
# 与find类似但找不到子串时会引发异常
# print(str1.index('or'))
# print(str1.index('shit'))
# 检查字符串是否以指定的字符串开头
print("str1.startswith('He') =", str1.startswith('He'))
print("str1.startswith('hel') =", str1.startswith('hel'))
# 检查字符串是否以指定的字符串结尾
print("str1.endswith('!') =", str1.endswith('!'))
# 将字符串以指定的宽度居中并在两侧填充指定的字符
print(str1.center(50, '*'))
# 将字符串以指定的宽度靠右放置左侧填充指定的字符
print(str1.rjust(50, ' '))
print('-'*80)
str2 = 'abc123456'
print(str2)
# 从字符串中取出指定位置的字符(下标运算)
print("str2[2] =", str2[2])
# 字符串切片(从指定的开始索引到指定的结束索引)
print("str2[2:5] =", str2[2:5])
print("str2[2:] =", str2[2:])
print("str2[2::2] =", str2[2::2]) # c246
print("str2[::2] =", str2[::2]) # ac246
print("str2[::-1] =", str2[::-1]) # 654321cba
print("str2[-3:-1] =", str2[-3:-1]) # 45
# 检查字符串是否由数字构成
print("str2.isdigit() =", str2.isdigit()) # False
# 检查字符串是否以字母构成
print("str2.isalpha() =", str2.isalpha()) # False
# 检查字符串是否以数字和字母构成
print("str2.isalnum() =", str2.isalnum()) # True
print('-'*80)
str3 = ' [email protected] '
print(str3)
# 获得字符串修剪左右两侧空格的拷贝
print("str3.strip() =", str3.strip())
if __name__ == '__main__':
main()
hello, world!
len(str1) = 13
str1首字母大写 = Hello, world!
str1变大写 = HELLO, WORLD!
str1.find('or') = 8
str1.find('shit') = -1
str1.startswith('He') = False
str1.startswith('hel') = True
str1.endswith('!') = True
******************hello, world!*******************
hello, world!
--------------------------------------------------------------------------------
abc123456
str2[2] = c
str2[2:5] = c12
str2[2:] = c123456
str2[2::2] = c246
str2[::2] = ac246
str2[::-1] = 654321cba
str2[-3:-1] = 45
str2.isdigit() = False
str2.isalpha() = False
str2.isalnum() = True
--------------------------------------------------------------------------------
[email protected]
str3.strip() = [email protected]
def main():
"""
定义和使用列表 / 用下表访问元素 / 下标越界 / 修改元素 / 添加元素 / 删除元素
"""
# 定义列表
list1 = [1, 3, 5, 7, 100]
print("list1 =", list1)
list2 = ['hello'] * 5 # 复制5个元素
print("list2 =", list2)
print('-'*50)
# 计算列表长度(元素个数)
print("len(list1) =", len(list1))
print('-'*50)
# 通过下标访问元素
print("list1[0] =", list1[0])
print("list1[4] =", list1[4])
# print(list1[5]) # IndexError: list index out of range 下标越界
print("list1[-1] =", list1[-1])
print("list1[-3] =", list1[-3])
print('-'*50)
# 修改元素
list1[2] = 300
print("list1[2]=300修改后 :", list1)
print('-'*50)
# 添加元素
list1.append(200)
list1.insert(1, 400)
list1 += [1000, 2000]
print("list1添加插入元素后 :", list1)
print('-'*50)
# 删除元素
del list1[0]
list1.pop()
list1.pop(-1)
list1.remove(3)
print("list1删除元素后:", list1)
print('-'*50)
# 清空列表元素
list1.clear()
print("list1.clear() =", list1)
if __name__ == '__main__':
main()
list1 = [1, 3, 5, 7, 100]
list2 = ['hello', 'hello', 'hello', 'hello', 'hello']
--------------------------------------------------
len(list1) = 5
--------------------------------------------------
list1[0] = 1
list1[4] = 100
list1[-1] = 100
list1[-3] = 5
--------------------------------------------------
list1[2]=300修改后 : [1, 3, 300, 7, 100]
--------------------------------------------------
list1添加插入元素后 : [1, 400, 3, 300, 7, 100, 200, 1000, 2000]
--------------------------------------------------
list1删除元素后: [400, 300, 7, 100, 200]
--------------------------------------------------
list1.clear() = []
def main():
"""
循环遍历 / 切片 / 复制 / 倒转 / 排序
"""
fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango'] # 列表添加元素
# 循环遍历列表元素
for fruit in fruits:
print(fruit.title(), end=' ')
print()
# 列表切片
fruits2 = fruits[1:4] # 切片复制元素
print("fruits2=fruits[1:4] =", fruits2)
print('-'*50)
# fruit3 = fruits # 没有复制列表只创建了新的引用
# 可以通过完整切片操作来复制列表
fruits3 = fruits[:]
print("fruits3 = fruits[:] =", fruits3)
fruits4 = fruits[-3:-1]
print("fruits4 = fruits[-3:-1] =", fruits4)
# 可以通过反向切片操作来获得倒转后的列表的拷贝
fruits5 = fruits[::-1] # [::-1]代表从后向前取值,每次步进值为1
print("fruits5 = fruits[::-1] =", fruits5)
print('-'*50)
# 排序函数
list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
# sorted函数返回列表排序后的拷贝,不会修改传入的列表
list2 = sorted(list1)
list3 = sorted(list1, reverse=True)
# 通过key关键字参数指定根据字符串长度进行排序而不是默认的字母表顺序
list4 = sorted(list1, key=len)
print("list1 =", list1)
print("list2 =", list2)
print("list3 =", list3)
print("list4 =", list4)
# 给列表对象发出排序消息直接在列表对象上进行排序
list1.sort(reverse=True)
print("list1.sort =", list1)
if __name__ == '__main__':
main()
Grape Apple Strawberry Waxberry Pitaya Pear Mango
fruits2=fruits[1:4] = ['apple', 'strawberry', 'waxberry']
--------------------------------------------------
fruits3 = fruits[:] = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']
fruits4 = fruits[-3:-1] = ['pitaya', 'pear']
fruits5 = fruits[::-1] = ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']
--------------------------------------------------
list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
list2 = ['apple', 'blueberry', 'internationalization', 'orange', 'zoo']
list3 = ['zoo', 'orange', 'internationalization', 'blueberry', 'apple']
list4 = ['zoo', 'apple', 'orange', 'blueberry', 'internationalization']
list1.sort = ['zoo', 'orange', 'internationalization', 'blueberry', 'apple']
import sys
def fib(n):
"""
yield关键字将一个普通函数改造成生成器函数
生成斐波拉切数列的生成器
"""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
yield a
def main():
"""
使用range创建数字列表 / 生成表达式 / 生成器
"""
f1 = [x for x in range(1, 10)]
print("f1 =", f1)
f2 = [x + y for x in 'ABCDE' for y in '1234567']
print("f2 =", f2)
print('-'*50)
# 生成表达式
# 用列表的生成表达式语法创建列表容器
# 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
f3 = [x ** 2 for x in range(1, 10)]
print("sys.getsizeof(f3) =", sys.getsizeof(f3)) # 查看对象占用内存的字节数
print("f3 =", f3[:20])
print('-'*50)
# 生成器
# 请注意下面的代码创建的不是一个列表而是一个生成器对象
# 通过生成器可以获取到数据但它不占用额外的空间存储数据
# 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)
f4 = (x ** 2 for x in range(1, 10))
print("sys.getsizeof(f4) =", sys.getsizeof(f4)) # 相比生成式生成器不占用存储数据的空间
print("f4 =", f4)
for val in f4:
print("f4 =", val)
print('-'*50)
# 生成斐波拉切数列
for val in fib(20):
print("fib(20) =", val)
print()
if __name__ == '__main__':
main()
f1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
f2 = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7', 'E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7']
--------------------------------------------------
sys.getsizeof(f3) = 100
f3 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
--------------------------------------------------
sys.getsizeof(f4) = 64
f4 = . at 0x03CD2870>
f4 = 1
f4 = 4
f4 = 9
f4 = 16
f4 = 25
f4 = 36
f4 = 49
f4 = 64
f4 = 81
--------------------------------------------------
fib(20) = 1
fib(20) = 1
fib(20) = 2
fib(20) = 3
fib(20) = 5
fib(20) = 8
fib(20) = 13
fib(20) = 21
fib(20) = 34
fib(20) = 55
fib(20) = 89
fib(20) = 144
fib(20) = 233
fib(20) = 377
fib(20) = 610
fib(20) = 987
fib(20) = 1597
fib(20) = 2584
fib(20) = 4181
fib(20) = 6765
def main():
"""
元组与列表类似,不同之处在于元组的元素不能修改
定义元组 / 使用元组中的值 / 修改元组变量 / 元组和列表转换
"""
# 定义元组
t = ('五月猴', 27, True, '广州深圳')
print("ty元组 =", t)
# 获取元组中的元素
print("t[0] =", t[0])
print("t[3] =", t[3])
# 遍历元组中的值
for member in t:
print("遍历t中的元素 =", member)
# 重新给元组赋值
# t[0] = '王大锤' # TypeError
# 变量t重新引用了新的元组原来的元组将被垃圾回收
t = ('王大锤', 20, True, '云南昆明')
print("t重新赋值 =", t)
# 将元组转换成列表
person = list(t)
print("list(t) =", person)
# 将列表转换成元组
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print("tuple(fruits_list) =", fruits_tuple)
if __name__ == '__main__':
main()
ty元组 = ('五月猴', 27, True, '广州深圳')
t[0] = 五月猴
t[3] = 广州深圳
遍历t中的元素 = 五月猴
遍历t中的元素 = 27
遍历t中的元素 = True
遍历t中的元素 = 广州深圳
t重新赋值 = ('王大锤', 20, True, '云南昆明')
list(t) = ['王大锤', 20, True, '云南昆明']
tuple(fruits_list) = ('apple', 'banana', 'orange')
def main():
"""
集合和列表的区别 / 创建集合 / 添加元素 / 删除元素 / 清空
"""
# 创建集合1
set1 = {
1, 2, 3, 3, 3, 2}
print("set1 =", set1)
print('set1_Length =', len(set1))
# 创建集合2
set2 = set(range(1, 10))
print("set2 =", set2)
print('-'*50)
# 集合添加元素
set1.add(4)
set1.add(5)
print("set1.add(4/5)后:",set1)
# 集合更新元素
set2.update([11, 12])
print("set2.update([11, 12])后:", set2)
print('-'*50)
# 集合删除元素
set2.discard(5)
# remove的元素如果不存在会引发KeyError
if 4 in set2:
set2.remove(4)
print("set2.discard(5)/set2.remove(4)后:", set2)
# # 遍历集合容器
# for elem in set2:
# print("遍历集合set2 =", elem ** 2, end=' ')
# print()
print('-'*50)
# 将元组转换成集合
set3 = set((1, 2, 3, 3, 2, 1))
print(set3.pop())
print("元组转为集set3 =", set3)
if __name__ == '__main__':
main()
set1 = {1, 2, 3}
set1_Length = 3
set2 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
--------------------------------------------------
set1.add(4/5)后: {1, 2, 3, 4, 5}
set2.update([11, 12])后: {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12}
--------------------------------------------------
set2.discard(5)/set2.remove(4)后: {1, 2, 3, 6, 7, 8, 9, 11, 12}
--------------------------------------------------
1
元组转为集set3 = {2, 3}
def main():
"""
交集 / 并集 / 差集 / 对称差 / 子集 / 超集
"""
# 创建集合
set1 = set(range(1, 7))
set2 = set(range(2, 11, 2))
set3 = set(range(1, 5))
print("set1 =", set1)
print("set2 =", set2)
print("set3 =", set3)
print('-'*50)
# 集合的交集、并集、差集、对称差运算
print("set1 & set2 =", set1 & set2)
# print(set1.intersection(set2))
print("set1 | set2 =", set1 | set2)
# print(set1.union(set2))
print("set1 - set2 =", set1 - set2)
# print(set1.difference(set2))
print("set1 ^ set2 =", set1 ^ set2)
# print(set1.symmetric_difference(set2))
print('-'*50)
# 判断子集和超集
print("set2 <= set1 =", set2 <= set1)
# print(set2.issubset(set1))
print("set3 <= set1 =", set3 <= set1)
# print(set3.issubset(set1))
print("set1 >= set2 =", set1 >= set2)
# print(set1.issuperset(set2))
print("set1 >= set3 =", set1 >= set3)
# print(set1.issuperset(set3))
if __name__ == '__main__':
main()
set1 = {1, 2, 3, 4, 5, 6}
set2 = {2, 4, 6, 8, 10}
set3 = {1, 2, 3, 4}
--------------------------------------------------
set1 & set2 = {2, 4, 6}
set1 | set2 = {1, 2, 3, 4, 5, 6, 8, 10}
set1 - set2 = {1, 3, 5}
set1 ^ set2 = {1, 3, 5, 8, 10}
--------------------------------------------------
set2 <= set1 = False
set3 <= set1 = True
set1 >= set2 = False
set1 >= set3 = True
def main():
"""
字典的特点:典的每个元素都是由一个键和一个值组成的“键值对”,键和值通过冒号分开
创建字典 / 添加元素 / 删除元素 / 取值 / 清空
"""
# 创建字典
scores = {
'五月猴': 92, '白元芳': 78, '狄仁杰': 82}
# 通过键可以获取字典中对应的值
print("scores['五月猴'] =", scores['五月猴'])
print("scores['狄仁杰'] =", scores['狄仁杰'])
# 对字典进行遍历(遍历的其实是键再通过键取对应的值)
for elem in scores:
print("遍历scores中元素:", '%s\t--->\t%d' % (elem, scores[elem]))
print('-'*50)
# 更新字典中的元素
scores['白元芳'] = 65
scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85)
print("更新scores后 =", scores)
print('-'*50)
# get方法也是通过键获取对应的值但是可以设置默认值
if '武则天' in scores:
print(scores['武则天'])
print("scores.get('武则天') =", scores.get('武则天'))
print("scores.get('武则天', 60) =", scores.get('武则天', 60))
print('-'*50)
# 删除字典中的元素
print("scores.popitem() =", scores.popitem())
print("scores.popitem() =", scores.popitem())
print("scores.pop('五月猴', 100) =", scores.pop('五月猴', 100))
print("scores =", scores)
# 清空字典
scores.clear()
print("scores.clear() =",scores)
if __name__ == '__main__':
main()
scores['五月猴'] = 92
scores['狄仁杰'] = 82
遍历scores中元素: 五月猴 ---> 92
遍历scores中元素: 白元芳 ---> 78
遍历scores中元素: 狄仁杰 ---> 82
--------------------------------------------------
更新scores后 = {'五月猴': 92, '白元芳': 65, '狄仁杰': 82, '诸葛王朗': 71, '冷面': 67, '方启鹤': 85}
--------------------------------------------------
scores.get('武则天') = None
scores.get('武则天', 60) = 60
--------------------------------------------------
scores.popitem() = ('方启鹤', 85)
scores.popitem() = ('冷面', 67)
scores.pop('五月猴', 100) = 92
scores = {'白元芳': 65, '狄仁杰': 82, '诸葛王朗': 71}
scores.clear() = {}
def main():
"""
keys()方法 / values()方法 / items()方法 / setdefault()方法
"""
stu = {
'name': '五月猴', 'age': 27, 'gender': True}
print("stu =", stu)
print(stu.keys())
print(stu.values())
print(stu.items())
print('-'*80)
for elem in stu.items():
print("elem =", elem)
print("elem[0],elem[1] =", elem[0], elem[1])
print('-'*80)
if 'age' in stu:
stu['age'] = 20
print("stu['age'] = 20 :", stu)
print('-'*80)
stu.setdefault('score', 60)
print("stu.setdefault('score', 60) =", stu)
stu.setdefault('score', 100)
print("stu.setdefault('score', 100) =", stu)
stu['score'] = 100
print("stu['score'] = 100 :", stu)
if __name__ == '__main__':
main()
stu = {'name': '五月猴', 'age': 27, 'gender': True}
dict_keys(['name', 'age', 'gender'])
dict_values(['五月猴', 27, True])
dict_items([('name', '五月猴'), ('age', 27), ('gender', True)])
--------------------------------------------------------------------------------
elem = ('name', '五月猴')
elem[0],elem[1] = name 五月猴
elem = ('age', 27)
elem[0],elem[1] = age 27
elem = ('gender', True)
elem[0],elem[1] = gender True
--------------------------------------------------------------------------------
stu['age'] = 20 : {'name': '五月猴', 'age': 20, 'gender': True}
--------------------------------------------------------------------------------
stu.setdefault('score', 60) = {'name': '五月猴', 'age': 20, 'gender': True, 'score': 60}
stu.setdefault('score', 100) = {'name': '五月猴', 'age': 20, 'gender': True, 'score': 60}
stu['score'] = 100 : {'name': '五月猴', 'age': 20, 'gender': True, 'score': 100}
"""
在屏幕上显示跑马灯文字
"""
import os
import time
def main():
content = '北京欢迎你为你开天辟地…………'
count=0
while True:
# 清理屏幕上的输出
os.system('clear') # os.system('cls')
print(content)
# 休眠200毫秒
time.sleep(0.2)
content = content[1:] + content[0]
# 满20次中断循环
count+=1
if count==10:
break
if __name__ == '__main__':
main()
北京欢迎你为你开天辟地…………
京欢迎你为你开天辟地…………北
欢迎你为你开天辟地…………北京
迎你为你开天辟地…………北京欢
你为你开天辟地…………北京欢迎
为你开天辟地…………北京欢迎你
你开天辟地…………北京欢迎你为
开天辟地…………北京欢迎你为你
天辟地…………北京欢迎你为你开
辟地…………北京欢迎你为你开天
"""
找出列表中最大、第二大或最小的元素
"""
def main():
fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya']
# 直接使用内置的max和min函数找出列表中最大和最小元素
# print(max(fruits))
# print(min(fruits))
# (1)寻找最大、最小元素
max_value = min_value = fruits[0]
for index in range(1, len(fruits)):
if fruits[index] > max_value:
max_value = fruits[index]
elif fruits[index] < min_value:
min_value = fruits[index]
print('Max:', max_value)
print('Min:', min_value)
print('-'*50)
# (2)寻找最大及第二大元素
Max1 ,Max2 = (fruits[0], fruits[1]) if fruits[0] > fruits[1] else (fruits[1], fruits[0])
for index in range(2, len(fruits)):
if fruits[index] > Max1:
Max2 = Max1
Max1 = fruits[index]
elif fruits[index] > Max2:
Max2 = fruits[index]
print('Max1:', Max1)
print('Max2:', Max2)
if __name__ == '__main__':
main()
Max: waxberry
Min: apple
--------------------------------------------------
Max1: waxberry
Max2: strawberry
"""
输入学生考试成绩计算平均分
"""
def main():
number = int(input('请输入学生人数: '))
names = [None] * number
scores = [None] * number
for index in range(len(names)):
names[index] = input('请输入第%d个学生的名字: ' % (index + 1))
scores[index] = float(input('请输入第%d个学生的成绩: ' % (index + 1)))
total = 0
for index in range(len(names)):
print('%s: %.1f分' % (names[index], scores[index]))
total += scores[index]
print('平均成绩是: %.1f分' % (total / number))
if __name__ == '__main__':
main()
请输入学生人数: 3
请输入第1个学生的名字: name1
请输入第1个学生的成绩: 60
请输入第2个学生的名字: name2
请输入第2个学生的成绩: 90
请输入第3个学生的名字: name3
请输入第3个学生的成绩: 70
name1: 60.0分
name2: 90.0分
name3: 70.0分
平均成绩是: 73.3分
"""
生成斐波拉切数列
"""
def main():
f = [1 , 1]
for i in range(2, 20):
f += [f[i - 1] + f[i - 2]]
# f.append(f[i - 1] + f[i - 2])
for val in f:
print(val, end=' ')
if __name__ == '__main__':
main()
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
"""
输出10行的杨辉三角 - 二项式的n次方展开系数
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
... ... ...
"""
def main():
num = int(input('Number of rows: '))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None] * (row + 1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
print(yh[row][col], end='\t')
print()
if __name__ == '__main__':
main()
Number of rows: 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
"""
设计一个函数产生指定长度的验证码,验证码由大小写字母和数字构成
"""
import random
def main(code_len=4):
"""
生成指定长度的验证码
:param code_len: 验证码的长度(默认4个字符)
:return: 由大小写英文字母和数字构成的随机验证码
"""
all_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
last_pos = len(all_chars) - 1
code = ''
for _ in range(code_len):
index = random.randint(0, last_pos)
code += all_chars[index]
print(code)
if __name__ == '__main__':
main()
IBzY
"""
设计一个函数返回给定文件名的后缀名
"""
def main(filename, has_dot=False):
"""
获取文件名的后缀名
:param filename: 文件名
:param has_dot: 返回的后缀名是否需要带点
:return: 文件的后缀名
"""
pos = filename.rfind('.')
if 0 < pos < len(filename) - 1:
index = pos if has_dot else pos + 1
print(filename[index:])
else:
print('')
if __name__ == '__main__':
main('test.csv')
csv
"""
计算指定的年月日是这一年的第几天
"""
def is_leap_year(year):
"""
判断指定的年份是不是闰年
:param year: 年份
:return: 闰年返回True平年返回False
"""
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
def which_day(year, month, date):
"""
计算传入的日期是这一年的第几天
:param year: 年
:param month: 月
:param date: 日
:return: 第几天
"""
days_of_month = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
,[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]][is_leap_year(year)]
total = 0
for index in range(month - 1):
total += days_of_month[index]
return total + date
def main():
print(which_day(1980, 11, 28))
print(which_day(1981, 12, 31))
print(which_day(2018, 1, 1))
print(which_day(2016, 3, 1))
if __name__ == '__main__':
main()
333
365
1
61
"""
双色球随机选号程序
"""
from random import randrange, randint, sample
def display(balls):
"""
输出列表中的双色球号码
"""
for index, ball in enumerate(balls):
if index == len(balls) - 1:
print('|', end=' ')
print('%02d' % ball, end=' ')
print()
def random_select():
"""
随机选择一组号码
"""
red_balls = [x for x in range(1, 34)]
selected_balls = []
for _ in range(6):
index = randrange(len(red_balls))
selected_balls.append(red_balls[index])
del red_balls[index]
# 上面的for循环也可以写成下面这行代码
# sample函数是random模块下的函数
# selected_balls = sample(red_balls, 6)
selected_balls.sort()
selected_balls.append(randint(1, 16))
return selected_balls
def main():
n = int(input('机选几注: '))
for _ in range(n):
display(random_select())
if __name__ == '__main__':
main()
机选几注: 2
06 14 16 23 29 33 | 16
02 04 08 25 28 31 | 10