03.python面试之模块与包

在编程中多多使用函数,模块和包能够提升模块化编程。

模块与包

输入日期, 判断这一天是这一年的第几天?

1
2
3
4
5
6
7
8
9
10
11
# 转为timetuple计算
import datetime
def get_days():
year = 2022
month = 2
day = 11
date_current = datetime.datetime(year=year, month=month, day=day)
# 转为time元组
time_tuple = date_current.timetuple()
return time_tuple.tm_yday
get_days()
42
1
2
3
4
5
6
7
8
9
# 计算时间差
def get_days():
year = 2022
month = 2
day = 11
date_first = datetime.datetime(year=year, month=1, day=1)
date_current = datetime.datetime(year=year, month=month, day=day)
return (date_current - date_first).days + 1
get_days()
42

打乱一个排好序的list对象alist

1
2
3
4
5
# 使用内置方法
import random
alist = [1,2,3,4,5]
random.shuffle(alist)
print(alist)
[2, 3, 4, 5, 1]
1
2
3
4
5
6
7
8
9
10
11
12
13
import random
# 随机取出元素放入另一个列表中
alist = [1,2,3,4,5]
results = []
for i in range(len(alist)):
# 随机取出一个元素
random_item = random.choice(alist)
# 将该元素添加至新列表
results.append(random_item)
# 原列表中删除该元素
alist.remove(random_item)
results

[2, 5, 3, 4, 1]