基础部分:模块与包
python# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 3_输入日期,判断是这一天是这一年的第几天
# Description: 如:输入"2023-3-12",输出"2023-3-12是2023年的第71天"
# Author: zhaoyaowei
# Date: 2023/3/12 14:26
# -------------------------------------------------------------------------------
import datetime
def get_days():
"""
方法一:
需考虑年份是否为闰年,月份是否大于2
:return: 示例:2023-3-12是2023年的第71天
"""
s = input("请输入日期, 格式为yyyy-mm-dd:")
year, month, day = map(int, s.split("-"))
# 默认根据平年月份计算天数
months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
# 判断输入月份是否正确
if 1 <= month <= 12:
total = months[month-1]
total += day
leap = 0
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
leap = 1
# 判断输入日期是否正确
days = [31, 28 + leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if day > days[month-1]:
print("输入的日期错误")
else:
# 若为闰年且月份大于2,则天数增加一天
if month > 2 and leap == 1:
total += 1
print(f"{s}是{year}年的第{total}天")
else:
print("输入的月份错误")
def get_days1():
"""
方法二:采用python的内置模块datetime
:return: 示例:2023-3-12是2023年的第71天
"""
s = input("请输入日期, 格式为yyyy-mm-dd:")
year, month, day = map(int, s.split("-"))
date1 = datetime.date(year, month, day)
date2 = datetime.date(year, 1, 1)
# 计算天数差,若date2传餐(year, 12, 31),则最终无需+1
total = (date1 - date2).days + 1
print(f"{s}是{year}年的第{total}天")
if __name__ == '__main__':
get_days1()
python# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 4_打乱一个排好序的list对象alist?
# Description: alist = [1,2,3,4,5]
# Author: zhaoyaowei
# Date: 2023/3/12 19:41
# -------------------------------------------------------------------------------
import random
alist = [1, 2, 3, 4, 5]
# 方法一:不会生成新的列表,仅打乱原列表的次序
random.shuffle(alist)
print(alist)
# 方法二:
blist = random.sample(alist, len(alist))
print(blist)
# 附录:
"""
random库用于生成随机数
一、随机种子seed()
(1)seed(a=None) 初始化给定的随机数种子,默认为当前系统时间
random.seed(10) #产生种子10对应的序列
二、随机整数
(1)randint(a, b) 生成一个[a, b]之间的整数,左闭右闭
(2)randrange(a) 生成[0, a)之间的随机整数,左闭右开
(3)randrange(a, b, step) 生成[a, b)之间以setp为步长的随机整数,左闭右开
三、随机浮点数
(1)random() 生成一个[0.0, 1.0)之间的随机浮点数
(2)uniform(a, b) 生成[a, b]之间的随机浮点数
四、序列函数
(1)choice(seq) 从序列seq中随机选择一个元素
(2)choices(seq,weights=None, k) 对序列类型进行k次重复采样,可设置权重,权重小的说明被取到的概率更小
choices(['a', 'b', 'c'], [4,4,2], k=10) # 这里的[4,4,2]就是每个元素分别对应的权重
(3)shuffle(seq) 将序列seq中元素随机排列,返回打乱后的序列
(4)sample(pop, k) 从pop类型中随机选取k个元素,返回列表,k <= len(list)
"""
本文作者:赵耀伟
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!