标签: 移除

  • python集合元素的删除

    在Python中,集合(set)是一个无序的数据结构,它不保持元素的插入顺序。因此,当你print一个集合时,元素的输出顺序可能看起来是随机的,实际上这个顺序是由集合内部的哈希表决定的。

    attendees = {'Alice Smith', 'Bob Jones', 'Carol', 'David'}
    print(attendees)
    

    它输出的结果可能有点出人意料。

    展开/折叠结果 >>> print(attendees)
    {'Carol', 'Alice Smith', 'Bob Jones', 'David'}

    这体现了集合的无序性,如果我们想从中删除元素,比较适合和安全的方法是写一个函数。

    def remove_attendees_with_first_name(attendees, name):   # 定义一个函数
        to_remove = set()   # 新建一个空集合
        for att in attendees:   # for循环,循环attendees的每一个元素
            if att.startswith(name):   # 检查每一个元素,是否是以给定的name变量开头
                to_remove.add(att)   # 如果是,把该元素放入新建的集合
        for remove in to_remove:   # 第二个for循环,遍历新建的集合
            attendees.discard(remove)   # 从attendees集合中移除to_remove集合中的每一个元素
    remove_attendees_with_first_name(attendees, 'Bob')   # 我们移除Bob开头的元素
    print(attendees)  # 输出将不包含 'Bob Jones'
    
    展开/折叠结果 >>> remove_attendees_with_first_name(attendees, 'Bob')
    >>> print(attendees) # 输出将不包含 'Bob Jones'
    {'Carol', 'Alice Smith', 'David'}