我正在寻找一种更简单的方式或更好的实践来简化数据过滤。基本上,我有类结构的数据,并且我想选择和分组属性。有没有一种好的方法可以做到这一点,而不是平面化到表格格式?
示例:
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)发布于 2015-01-04 15:55:54
你可以像这样使用列表理解:
result = [square for square in colorindex['black'] if square in XYindex['0,0']]当逻辑不复杂时,列表理解是过滤数据的一种简单方法。
https://stackoverflow.com/questions/27762405
复制相似问题