一.关系运算
有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
1. 求出即报名python又报名linux课程的学员名字集合
print(pythons & linuxs)
2. 求出所有报名的学生名字集合
print(pythons | linuxs)
3. 求出只报名python课程的学员名字
print(pythons - linuxs)
4. 求出没有同时这两门课程的学员名字集合
print(pythons ^ linuxs)
二.去重
1. 有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序
l = ['a', 'b', 1, 'a', 'a']
new_list = list(set(l))
print(new_list)
2.在上题的基础上,保存列表原来的顺序
l = ['a', 'b', 1, 'a', 'a']
# 根据顺序去重
new_list = []
for line in l:
if line not in new_list:
new_list.append(line)
print(new_list)
3.去除文件中重复的行,肯定要保持文件内容的顺序不变
# 本地创建一个 file.txt 文件
'''
文件内容如下:
aaa
bbb
ccc
ddd
aaa
bbb
ccc
ggg
tank
egon
'''
new_list = []
# 打开文件,一行一行读取出来
with open('file.txt', 'r', encoding='utf-8') as f:
for line in f:
# print(line)
if line not in new_list:
new_list.append(line)
print(new_list)
# 将去重后的数据,写入到文件中
with open('new_file.txt', 'w', encoding='utf-8') as f:
for line in new_list:
f.write(line)
4.有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序
l=[
{'name':'egon','age':18,'sex':'male'},
{'name':'alex','age':73,'sex':'male'},
{'name':'egon','age':20,'sex':'female'},
{'name':'egon','age':18,'sex':'male'},
{'name':'egon','age':18,'sex':'male'},
]
new_list = []
for dic in l:
if dic not in new_list:
new_list.append(dic)
print(new_list)