用三个集合表示三门学科的选课学生姓名(一个学生可以同时选多门课)
s_history = {'小明', "张三", '李四', "王五", 'Lily', "Bob"}
s_politic = {'小明', "小花", '小红', "二狗"}
s_english = {'小明', 'Lily', "Bob", "Davil", "李四"}
a. 求选课学生总共有多少人
print("选课学生总共有", len(s_english | s_politic | s_history), '人')
b. 求只选了第一个学科的人的数量和对应的名字
print('只选了第一个学科的人的数量:', len(s_history - s_politic - s_english), '姓名:', s_history - s_politic - s_english)
c. 求只选了一门学科的学生的数量和对应的名字
s1 = s_history - s_politic - s_english
s2 = s_english - s_politic - s_history
s3 = s_politic - s_english - s_history
print('只选了一门学科的学生的数量:', len(s1 | s2 | s3), '姓名:', s1 | s2 | s3)
d. 求只选了两门学科的学生的数量和对应的名字
s = s_english & s_history & s_politic
s1 = s_history & s_politic - s
s2 = s_english & s_politic - s
s3 = s_history & s_english - s
print('只选了两门学科的学生的数量:', len(s1 | s2 | s3), '姓名:', s1 | s2 | s3)
e. 求选了三门学生的学生的数量和对应的名字
print('选了三门学生的学生的数量:', len(s_english & s_politic & s_history), '姓名:', s_english & s_politic & s_history)
获取列表中出现次数最多的元素
例如:nums = [1, 2, 3,1,4,2,1,3,7,3,3] —> 打印:3
nums = [1,2,2,1,3] --> 打印1、2
nums = [1, 2, 3,1,4,2,1,3,7,3,3]
max_count =[]
for i in list(set(nums)):
max_count.append(nums.count(i))
for j in range(len(num_dict_li)):
if max_count[j]==max(max_count):
print(num_dict_li[j])
#详解:
nums = [1, 2, 3, 1, 4, 2, 1, 3, 7, 3, 3]
# 1)去重获取不重复的元素
new_nums = list(set(nums)) # [1,2,3,4,7]
# 2)统计每个元素出现的次数
count = []
for x in new_nums:
count.append(nums.count(x)) # [3,2,4,1,1]
# 3)获取最大次数
max_count = max(count)
# 4)获取最大次数对应的元素
for index in range(len(count)):
if count[index] == max_count:
print(new_nums[index])
实现给定一个日期,判断这个日期是今年第几天的程序(尝试)
> 例如:2022/12/31 --> 今年第365天;2022/1/1 --> 今年第1天
# 1)先把年月日依次取出来,后面对数字操作,所以将转换成int
date = '2022/03/16'
year = int(date[0:4])
month = int(date[5:7])
day = int(date[-2:])
# 2)
'''
1月:day
2月:31 + day
3月:31 + 28/29 +day
4月:31 + 28、29 + 31 + day
...
'''
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 1:
total_days = day
else:
total_days = sum(days[:month - 1]) + day
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
total_days += 1
print(total_days)