【问题标题】:Indexing Heirarchial Data with Python使用 Python 索引层次结构数据
【发布时间】:2023-03-04 21:27:02
【问题描述】:

我正在寻找一种更 Pythonic 的方式或更好的做法来简化过滤数据。基本上,我有类结构化数据,我想选择和分组属性。有没有一种不用扁平化为表格格式的好方法?

例子:

class Point:
    def __init__(self, x, y)
        self.x = x
        self.y = y

class Square:
    def __init__(self,origin,length,rotation,color):
        self.origin = origin
        self.length = length
        ...


#populated with all squares
square_list = get_squares()

#create x,y map of all squares
XYindex = defaultdict(list)
for square in square_list:
    XYindex[str(square.origin.x)+','+str(square.origin.y)].append(square)


colorindex = defaultdict(list)
for square in square_list:
    colorindex[str(square.color)].append(square)

#find black squares at 0,0
result = []
for square in colorindex['black']:
    if square in XYindex['0,0']:
        result.append(square)

【问题讨论】:

    标签: python sorting indexing hierarchical-data


    【解决方案1】:

    你可以像这样使用列表推导:

    result = [square for square in colorindex['black'] if square in XYindex['0,0']]
    

    列表推导是在逻辑不复杂时过滤数据的简单方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2015-12-16
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多