Python-set的创建和读取
·
分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请轻击人工智能教程
https://www.captainai.net/troubleshooter
一、创建 set
1. 使用花括号 {}
# 直接创建
fruits = {'apple', 'banana', 'orange'}
print(fruits) # {'banana', 'orange', 'apple'}(无序)
# 注意:空花括号创建的是字典,不是集合
empty_dict = {} # 这是字典
empty_set = set() # 这才是空集合
2. 使用 set() 构造函数
# 从列表创建
colors = set(['red', 'green', 'blue'])
print(colors) # {'red', 'green', 'blue'}
# 从字符串创建(每个字符成为元素)
chars = set('hello')
print(chars) # {'h', 'e', 'l', 'o'}(注意:l 只出现一次,自动去重)
# 从元组创建
numbers = set((1, 2, 3, 3, 4))
print(numbers) # {1, 2, 3, 4}(自动去重)
# 创建空集合
empty = set()
3. 使用集合推导式
# 创建包含平方数的集合
squares = {x**2 for x in range(5)}
print(squares) # {0, 1, 4, 9, 16}
# 筛选条件
evens = {x for x in range(10) if x % 2 == 0}
print(evens) # {0, 2, 4, 6, 8}
二、读取和访问 set
重要特性:set 是无序的,不支持索引和切片,无法通过位置访问元素。
1. 遍历集合
fruits = {'apple', 'banana', 'orange'}
# 使用 for 循环遍历
for fruit in fruits:
print(fruit)
# 带索引的遍历(需要转换为列表)
for i, fruit in enumerate(fruits):
print(f"索引 {i}: {fruit}")
2. 成员检查
fruits = {'apple', 'banana', 'orange'}
# 检查元素是否存在
if 'apple' in fruits:
print("苹果在集合中") # 输出
if 'grape' not in fruits:
print("葡萄不在集合中") # 输出
3. 获取集合信息
# 获取集合大小
size = len(fruits)
print(f"集合大小: {size}") # 3
# 检查是否为空
if fruits:
print("集合不为空")
else:
print("集合为空")
4. 提取元素(转换为其他类型)
fruits = {'apple', 'banana', 'orange'}
# 转换为列表(获得有序列表)
fruit_list = list(fruits)
print(fruit_list[0]) # 可以索引访问,但顺序不确定
# 转换为元组
fruit_tuple = tuple(fruits)
# 转换为排序列表
sorted_fruits = sorted(fruits)
print(sorted_fruits) # ['apple', 'banana', 'orange'](排序后)
三、常用操作示例
# 创建集合
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# 成员检查
print(3 in set1) # True
# 遍历集合
for num in set1:
print(num, end=' ') # 输出: 1 2 3 4 5
# 使用 pop() 随机取出并删除一个元素
item = set1.pop()
print(f"取出: {item},剩余: {set1}")
# 获取所有元素(只能通过遍历)
def print_set(s):
for elem in s:
print(elem, end=' ')
print()
print_set(set2) # 输出集合的所有元素
更多推荐

所有评论(0)