Python算法 - 根据对象属性从列表中挑选对象

时间:2014-03-31 04:30:18

标签: python algorithm

我有一个自定义的Python对象,如:

    ID - string    
    Name - string
    Unit - string
    Weight - float

我在一个列表中包含所有可能的对象。 Unit属性可以是A-F的字符串值。我需要将此列表分解为具有1个具有Unit = A的对象的所有可能组合,1个具有Unit = B的对象,一直到F但是在F的情况下,我需要有3个对象,其中Unit = F。所有新列表都需要包含唯一项(即Unit = F对象必须是唯一的),并且所有结果列表也必须是唯一的。我完全迷失了如何创建这样的算法。有人可以提供一些想法和/或伪代码吗?

1 个答案:

答案 0 :(得分:3)

在这种情况下,您可能会发现itertools非常有用,尤其是函数itertools.productitertools.combinations

以下是根据您的说明创建的示例:

from itertools import product, combinations

class Blob:

    def __init__(self, ID, Name, Unit, Weight):
        self.ID = ID  
        self.Name = Name
        self.Unit = Unit
        self.Weight = Weight

    def __repr__(self):
        return 'Object: ID={ID}, Name={Name}, Unit={Unit}, Weight={Weight}'.format(Name=self.Name, ID=self.ID, Unit=self.Unit, Weight=self.Weight)

blobs = [Blob(1, 'AA', 'A', 1.0),
         Blob(2, 'AA', 'A', 1.0),
         Blob(3, 'AA', 'B', 1.0),
         Blob(4, 'AA', 'B', 1.0),
         Blob(5, 'AA', 'C', 1.0),
         Blob(6, 'AA', 'C', 1.0),
         Blob(7, 'AA', 'D', 1.0),
         Blob(8, 'AA', 'D', 1.0),
         Blob(9, 'AA', 'E', 1.0),
         Blob(10,'AA', 'E', 1.0),
         Blob(11,'AA', 'F', 1.0),
         Blob(12,'AA', 'F', 1.0),
         Blob(13,'AA', 'F', 1.0),
         Blob(14,'AA', 'F', 1.0)]

# Break down into selectable sub-groups by unit name
groups = {k: [b for b in blobs if b.Unit==k] for k in ['A','B','C','D','E','F']}
# Special treatment for unit F: expand to combination chunks of length 3
groups['F'] = combinations(groups['F'], 3)
# Create the list of all combinations
selected = list(product(*groups.values()))

一些示例输出:

>>> selected[0]
(Object: ID=1, Name=AA, Unit=A, Weight=1.0,
 Object: ID=5, Name=AA, Unit=C, Weight=1.0,
 Object: ID=3, Name=AA, Unit=B, Weight=1.0,
 Object: ID=9, Name=AA, Unit=E, Weight=1.0,
 Object: ID=7, Name=AA, Unit=D, Weight=1.0,
 (Object: ID=11, Name=AA, Unit=F, Weight=1.0,
  Object: ID=12, Name=AA, Unit=F, Weight=1.0,
  Object: ID=13, Name=AA, Unit=F, Weight=1.0))

>>> selected[1]
(Object: ID=1, Name=AA, Unit=A, Weight=1.0,
 Object: ID=5, Name=AA, Unit=C, Weight=1.0,
 Object: ID=3, Name=AA, Unit=B, Weight=1.0,
 Object: ID=9, Name=AA, Unit=E, Weight=1.0,
 Object: ID=7, Name=AA, Unit=D, Weight=1.0,
 (Object: ID=11, Name=AA, Unit=F, Weight=1.0,
  Object: ID=12, Name=AA, Unit=F, Weight=1.0,
  Object: ID=14, Name=AA, Unit=F, Weight=1.0))

您可能希望将F作为最终列表中的单位展平元素。