此问题在此处已有答案:
How to get the cartesian product of a series of lists(17个答案)
4天前关闭。
variations = {
'size':{'small':'Small',
'medium':'Medium',
'large':'Large'},
'quantity':{'20l':'20l',
'10l':'10l',
'5l':'5l'},
'color':{'red':'Red',
'blue':'Blue',
'green':'Green'}
}
var_list = [[i,j,k] for i in variations['color'] for j in variations['size'] for k in variations['quantity']]
也可以将上面的代码编写为:
var_list = []
for i in variations['color']:
for j in variations['size']:
for k in variations['quantity']:
comb = []
comb.append(i)
comb.append(j)
comb.append(k)
Var_list.append(comb)
两个var_list输出:
[['red', 'small', '20l'], ['red', 'small', '10l'], ['red', 'small', '5l'], ['red', 'medium', '20l'], ['red', 'medium', '10l'], ['red', 'medium', '5l'], ['red', 'large', '20l'], ['red', 'large', '10l'], ['red', 'large', '5l'], ['blue', 'small', '20l'], ['blue', 'small', '10l'], ['blue', 'small', '5l'], ['blue', 'medium', '20l'], ['blue', 'medium', '10l'], ['blue', 'medium', '5l'], ['blue', 'large', '20l'], ['blue', 'large', '10l'], ['blue', 'large', '5l'], ['green', 'small', '20l'], ['green', 'small', '10l'], ['green', 'small', '5l'], ['green', 'medium', '20l'], ['green', 'medium', '10l'], ['green', 'medium', '5l'], ['green', 'large', '20l'], ['green', 'large', '10l'], ['green', 'large', '5l']]
var_list包含了3个for循环,基于变体中的3个字典。如何编写上面的代码,以便var_list中的for循环可以根据变体中存在的字典数量增加或减少?
例如,如果“brand”也出现在变量中,则应在var_list中动态创建此“brand”的for循环,因此var_list变为
var_list = [[i,j,k,l] for i in variations['color'] for j in variations['size'] for k in variations['quantity'] for l in varistions['brands']
1条答案
按热度按时间tkclm6bt1#
当我听到 *nested for循环 * 时,我认为 * 是..的乘积 *
得到
variations
的值的值的乘积。或者只是