有沒有辦法用itertools或numpy的假設兩種不同的情況下做到這一點?
使用itertools.product
from itertools import product
gender = ['male', 'female']
color = ['black', 'blue', 'red', 'green', 'yellow']
material = ['leather', 'fabric', 'cotton', 'wool']
size = ['xs', 's','m', 'l', 'xl']
for item in product(color, size, material, gender):
#do something()
你也可以使用一個generator expressions
for item in ((g, c, m, s) for g in gender for c in color for m in material for s in size):
#do something()
輸出
>>> for item in ((g, c, m, s) for g in gender for c in color for m in material for s in size):
... print(item)
...
('male', 'black', 'leather', 'xs')
('male', 'black', 'leather', 's')
('male', 'black', 'leather', 'm')
('male', 'black', 'leather', 'l')
('male', 'black', 'leather', 'xl')
('male', 'black', 'fabric', 'xs')
('male', 'black', 'fabric', 's')
('male', 'black', 'fabric', 'm')
('male', 'black', 'fabric', 'l')
('male', 'black', 'fabric', 'xl')
('male', 'black', 'cotton', 'xs')
('male', 'black', 'cotton', 's')
('male', 'black', 'cotton', 'm')
('male', 'black', 'cotton', 'l')
('male', 'black', 'cotton', 'xl')
('male', 'black', 'wool', 'xs')
('male', 'black', 'wool', 's')
('male', 'black', 'wool', 'm')
('male', 'black', 'wool', 'l')
('male', 'black', 'wool', 'xl')
('male', 'blue', 'leather', 'xs')
('male', 'blue', 'leather', 's')
('male', 'blue', 'leather', 'm')
('male', 'blue', 'leather', 'l')
('male', 'blue', 'leather', 'xl')
('male', 'blue', 'fabric', 'xs')
('male', 'blue', 'fabric', 's')
('male', 'blue', 'fabric', 'm')
('male', 'blue', 'fabric', 'l')
('male', 'blue', 'fabric', 'xl')
('male', 'blue', 'cotton', 'xs')
('male', 'blue', 'cotton', 's')
('male', 'blue', 'cotton', 'm')
('male', 'blue', 'cotton', 'l')
('male', 'blue', 'cotton', 'xl')
('male', 'blue', 'wool', 'xs')
('male', 'blue', 'wool', 's')
('male', 'blue', 'wool', 'm')
('male', 'blue', 'wool', 'l')
('male', 'blue', 'wool', 'xl')
('male', 'red', 'leather', 'xs')
('male', 'red', 'leather', 's')
('male', 'red', 'leather', 'm')
('male', 'red', 'leather', 'l')
('male', 'red', 'leather', 'xl')
('male', 'red', 'fabric', 'xs')
('male', 'red', 'fabric', 's')
('male', 'red', 'fabric', 'm')
('male', 'red', 'fabric', 'l')
('male', 'red', 'fabric', 'xl')
('male', 'red', 'cotton', 'xs')
('male', 'red', 'cotton', 's')
('male', 'red', 'cotton', 'm')
('male', 'red', 'cotton', 'l')
('male', 'red', 'cotton', 'xl')
('male', 'red', 'wool', 'xs')
('male', 'red', 'wool', 's')
('male', 'red', 'wool', 'm')
('male', 'red', 'wool', 'l')
...
- 如果每個維度中只能有一個關鍵字
- 如果每個維度可以有一個或幾個關鍵字
這兩種方法將工作,即使你的列表中有每一個元素。
你是什麼意思的'維度'和'number_of_dimensions'? – 2015-02-23 18:05:56
@ user5061這是一種不好的方式來說* iterables。我修正了這個問題。 – 2015-02-23 18:08:53