制作词典中的项的产品

问题描述 投票:0回答:1

假设我有以下状态列表:

states1 = ['one', 'two', 'four']
states2 = ['far away', 'normal', 'to close']
states3 = ['thor', 'iron man']

并且我想制造它们的产品

import itertools

state_indexes = [s for s in itertools.product(states1, states2, states3)]
print(state_indexes)

"""
[('one', 'far away', 'thor'), ('one', 'far away', 'iron man'), ('one', 'normal', 'thor'), ('one', 'normal', 'iron man'), ('one', 'to close', 'thor'), ('one', 'to close', 'iron man'), ('two', 'far away', 'thor'), ('two', 'far away', 'iron man'), ('two', 'normal', 'thor'), ('two', 'normal', 'iron man'), ('two', 'to close', 'thor'), ('two', 'to close', 'iron man'), ('four', 'far away', 'thor'), ('four', 'far away', 'iron man'), ('four', 'normal', 'thor'), ('four', 'normal', 'iron man'), ('four', 'to close', 'thor'), ('four', 'to close', 'iron 
man')]
"""

但是这是硬编码的方式,我想自动创建状态列表,所以我创建了这个字典:

my_dictionary = {}

for i in range(10):
    my_dictionary[f"item_{i}"] = ['state1', 'state2']

"""
{'item_0': ['state1', 'state2'], 'item_1': ['state1', 'state2'], 'item_2': ['state1', 'state2'], 'item_3': ['state1', 'state2'], 'item_4': ['state1', 'state2'], 'item_5': ['state1', 'state2'], 'item_6': ['state1', 'state2'], 'item_7': ['state1', 'state2'], 'item_8': ['state1', 'state2'], 'item_9': ['state1', 'state2']}
"""

直到现在可以使用,但是如何重新创建state_indexes列表?

这是我尝试的方法之一:

state_indexes = [s for s in itertools.product(my_dictionary)]
print(state_indexes)
"""
[('item_0',), ('item_1',), ('item_2',), ('item_3',), ('item_4',), ('item_5',), ('item_6',), ('item_7',), ('item_8',), ('item_9',)]
"""

我该如何解决?非常感谢]]

编辑:预期的输出基本上就是这个(如上例中所述):

"""
[('one', 'far away', 'thor'), ('one', 'far away', 'iron man'), ('one', 'normal', 'thor'), ('one', 'normal', 'iron man'), ('one', 'to close', 'thor'), ('one', 'to close', 'iron man'), ('two', 'far away', 'thor'), ('two', 'far away', 'iron man'), ('two', 'normal', 'thor'), ('two', 'normal', 'iron man'), ('two', 'to close', 'thor'), ('two', 'to close', 'iron man'), ('four', 'far away', 'thor'), ('four', 'far away', 'iron man'), ('four', 'normal', 'thor'), ('four', 'normal', 'iron man'), ('four', 'to close', 'thor'), ('four', 'to close', 'iron 
man')]
"""

所以看起来像这样(我知道这不是很直观,这就是我使用示例的原因)

"""
[('state1', 'state1', 'state1',...,'state1'), ('state1', 'state1',..., 'state2'),..., ('state2', 'state2',... ,'state2')]
"""

假设我有以下状态列表:States1 = ['一个”,“两个”,“四个”]状态2 = ['远处','正常','关闭']状态3 = ['thor', '钢铁侠'],我想将其制成商品进口...

python itertools multiplication
1个回答
2
投票

对于所有状态列表的乘积,您将必须使用*运算符解开字典的值:

© www.soinside.com 2019 - 2024. All rights reserved.