以下是一个示例代码,演示了如何按名称查找形状,按特定颜色查找并删除其他形状。
class Shape:
def __init__(self, name, color):
self.name = name
self.color = color
# 创建形状列表
shapes = [
Shape("圆形", "红色"),
Shape("矩形", "蓝色"),
Shape("三角形", "绿色"),
Shape("正方形", "红色"),
Shape("椭圆形", "黄色")
]
# 按名称查找形状
def find_shape_by_name(shapes, name):
found_shapes = []
for shape in shapes:
if shape.name == name:
found_shapes.append(shape)
return found_shapes
# 按特定颜色查找并删除其他形状
def delete_shapes_by_color(shapes, color):
shapes_to_delete = []
for shape in shapes:
if shape.color == color:
shapes_to_delete.append(shape)
for shape_to_delete in shapes_to_delete:
shapes.remove(shape_to_delete)
# 按名称查找形状示例
found_shapes = find_shape_by_name(shapes, "圆形")
for shape in found_shapes:
print("找到形状:", shape.name)
# 按特定颜色查找并删除其他形状示例
delete_shapes_by_color(shapes, "红色")
for shape in shapes:
print("剩余形状:", shape.name)
上述代码首先定义了一个 Shape
类,包含名称和颜色属性。然后创建了一个形状列表 shapes
。
接下来,定义了两个函数:
find_shape_by_name
函数按名称查找形状,遍历形状列表,将名称匹配的形状添加到一个新列表中,并返回该列表。delete_shapes_by_color
函数按特定颜色查找并删除形状,遍历形状列表,将颜色匹配的形状添加到一个新列表中,然后再遍历新列表,将其从原始形状列表中删除。最后,示例演示了如何使用这两个函数。首先按名称查找形状,并打印结果。然后按特定颜色查找并删除形状,并打印剩余的形状。