在這種情況下,您可能會發現itertools
非常有用,特別是功能itertools.product
和itertools.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
元素爲單位的最終名單。
itertools是你的朋友:https://docs.python.org/2/library/itertools.html –
好吧,這聽起來像沿着正確的線條。有人可以舉一個例子嗎?我認爲排列功能會給我我需要的東西嗎?不是100%肯定在那 –