返回

自定义类型集合判断是否包含某个子项的指南

闲谈

自定义类:

class Selection:
    def __init__(self, section, row):
        self.section = section
        self.row = row

    def __eq__(self, other):
        return self.section == other.section and self.row == other.row

使用自定义类:

  1. 初始化Selection对象列表:
selections = []
  1. 遍历字典列表,并为每个对象创建一个Selection对象:
for section_index, section in enumerate(tree_dict):
    for row_index, row in enumerate(section):
        selection = Selection(section_index, row_index)
        selections.append(selection)
  1. 定义一个List来保存选中的下标:
selected_indices = []
  1. 当用户选择一个对象时,将对应的Selection对象添加到selected_indices列表中:
def on_selection_changed(section_index, row_index):
    selection = Selection(section_index, row_index)
    if selection not in selected_indices:
        selected_indices.append(selection)
  1. 当用户取消选择一个对象时,将对应的Selection对象从selected_indices列表中移除:
def on_selection_removed(section_index, row_index):
    selection = Selection(section_index, row_index)
    if selection in selected_indices:
        selected_indices.remove(selection)
  1. 判断某个子项是否已被选中:
def is_selected(section_index, row_index):
    selection = Selection(section_index, row_index)
    return selection in selected_indices

完整示例:

class Selection:
    def __init__(self, section, row):
        self.section = section
        self.row = row

    def __eq__(self, other):
        return self.section == other.section and self.row == other.row

selections = []

for section_index, section in enumerate(tree_dict):
    for row_index, row in enumerate(section):
        selection = Selection(section_index, row_index)
        selections.append(selection)

selected_indices = []

def on_selection_changed(section_index, row_index):
    selection = Selection(section_index, row_index)
    if selection not in selected_indices:
        selected_indices.append(selection)

def on_selection_removed(section_index, row_index):
    selection = Selection(section_index, row_index)
    if selection in selected_indices:
        selected_indices.remove(selection)

def is_selected(section_index, row_index):
    selection = Selection(section_index, row_index)
    return selection in selected_indices

结论:

通过自定义一个类来存储字典列表中每个对象的下标,并通过一个List来保存选择的下标,可以轻松实现对树型结构的字典列表进行多选操作。这种方法简单易用,并且可以扩展到其他类似的数据结构中。