集合(Set)是Python中的一种无序、可变的数据结构,用于存储不重复的元素。集合使用大括号 {} 表示,也可以通过 set() 函数创建。
集合的特点:
集合中的元素通常是不可变类型(如数字、字符串、元组),不能像列表那样用索引访问元素。
# 创建集合
# fruits = {"苹果", "香蕉", "梨", "苹果"} # 自动去除重复的"苹果"
# print(fruits) # 输出时可能顺序不同
# 使用 set() 创建集合
letters = set("hello")
print(letters)
{'h', 'e', 'l', 'o'}
# 创建两个集合
A = {"中国", "法国", "美国"}
B = {"英国", "法国", "德国"}
# 添加元素
A.add("日本")
# 删除元素
B.discard("德国")
# 遍历集合
# for country in A:
# print(country)
# 并集(Union)
#print("并集:", A | B)
# # 交集(Intersection)
#print("交集:", A & B)
# # 差集(Difference)
#print("差集:", A - B)
# # 对称差集(Symmetric Difference)
print("对称差集:", A ^ B)
对称差集: {'中国', '英国', '日本', '美国'}
# 示例:比较两个文献中出现的关键词
keywords1 = {"改革", "开放", "经济", "现代化"}
keywords2 = {"民主", "开放", "科技", "现代化"}
# 找出两个文献都提到的关键词(交集)
print("共同关键词:", keywords1 & keywords2)
# 找出第一个文献独有的关键词
print("文献1独有关键词:", keywords1 - keywords2)
# 所有提到的关键词
print("总关键词集合:", keywords1 | keywords2)
共同关键词: {'现代化', '开放'}
文献1独有关键词: {'改革', '经济'}
总关键词集合: {'经济', '改革', '开放', '民主', '科技', '现代化'}
a_set = set(range(8,14))
b_set = set(range(9))
a_set.symmetric_difference(b_set) #对称差集
a = a_set^b_set #对称差集
a
{0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13}
使用集合快速提取序列中单一元素
import random
listRandom = [random.choice(range(10000)) for i in range(100)]
#listRandom
noRepeat = []
for i in listRandom:
if i not in noRepeat:
noRepeat.append(i)
print(len(listRandom))
print(len(noRepeat))
newSet = set(listRandom)
print(len(newSet))
100 99 99
请完成以下练习,并在下方代码框中编写代码:
# 练习1:不重复词汇集合
text = "人文 社科 历史 哲学 社科 文学"
words = set(text.split())
print("不重复词汇:", words)
# 练习2:比较学者常用词汇
scholar1 = {"文化", "符号", "意义", "认同"}
scholar2 = {"意义", "结构", "社会", "文化"}
print("共同词汇:", scholar1 & scholar2)
print("差异词汇:", scholar1 ^ scholar2)
# 练习3:课程选择对比
course_A = {"张三", "李四", "王五", "赵六"}
course_B = {"李四", "赵六"}
only_A = course_A - course_B
print("只选课程A的学生:", only_A)