【Python基础练习】实验3:列表、字典、集合

发布时间 2023-11-06 21:49:03作者: 萌狼蓝天

实验3:列表、字典、集合

姓名:萌狼蓝天

时间:2023年11月6日

Python:3.12

博客:https://wwww.mllt.cc

实验目的

(1)了解列表、元组、字典和集合的概念
(2)学习列表、元组、字典和集合对象的创建
(3)学习列表、元组、字典和集合函数的使用

实验内容及原理

1.已有列表lst = [1,2,3,4],lst2 = lst2 = ["a","b","c","d"]分别进行下面的操作

lst = [1,2,3,4]
lst2 = ["a","b","c","d"]
# 将两个列表合为一个列表lst3
lst3 = lst + lst2 
lst3
[1, 2, 3, 4, 'a', 'b', 'c', 'd']
lst3[:3]
[1, 2, 3]
lst3[2:5]
[3, 4, 'a']
lst3[1::2]
[2, 4, 'b', 'd']
lst3[-4:]
['a', 'b', 'c', 'd']

2.统计列表 lst=[12,2,16,30,28,10,16,20,6,18]

lst=[12,2,16,30,28,10,16,20,6,18]
# 元素个数
len(lst)
10
# 最大值
max(lst)
30
min(lst)
2
sum(lst)/len(lst)
15.8
sorted(lst)
[2, 6, 10, 12, 16, 16, 18, 20, 28, 30]

3.使用字典保存用户姓名和对应密码,输出所有用户姓名,并找出某个用户的密码。

info = {"张三":"zhangsan","李四":"lisi","王五":"wangwu"}
info.keys()
dict_keys(['张三', '李四', '王五'])
info.get("王五")
'wangwu'

4.使用元组分别保存学生姓名和对应成绩,找出最高分学生的姓名。

# 创建保存学生姓名和对应成绩的元组
students = (("张三", 85), ("李四", 90), ("王五", 80), ("赵六", 95))

# 初始化最高分和对应学生姓名
max_score = 0
max_student = ""

# 遍历每个学生的成绩
for student in students:
    # 如果该学生的成绩比当前最高分高,更新最高分和对应学生姓名
    if student[1] > max_score:
        max_score = student[1]
        max_student = student[0]

# 输出最高分学生的姓名
print("最高分学生的姓名为:", max_student)
最高分学生的姓名为: 赵六

5.输入一串字符,统计单词个数。

def count_words(text):
    words = text.split()
    return len(words)

# text = input("请输入一串字符: ")
text="张三 爱 李四 , Do you Konw ?"
count = count_words(text)
print("单词个数为:", count,"长度为",len(text))


单词个数为: 8 长度为 23

6.合并列表lst1=[3, 7, 44, 78, 6]和lst2=[35, 8, 59, 3, 47, 6]中的元素,并
将重复元素去除。

lst1 = [3, 7, 44, 78, 6]
lst2 = [35, 8, 59, 3, 47, 6]

merged_list = list(set(lst1 + lst2))

merged_list

[3, 35, 6, 7, 8, 44, 78, 47, 59]

实验步骤

(1) 进入conda环境,启动jupyter:jupyter notebook
(2)创建jupyter文件,编写代码