1

我有一个 Action 对象的元组

我想创建一个包含所有可能的 Action 对象 N 排列的列表。

即,如果我有吃、睡、喝和 N = 2 的动作

清单将是

[[Eat, Eat],
 [Eat, Sleep],
 [Eat, Drink],
 [Sleep, Eat],
 [Sleep, Sleep],
 [Sleep, Drink],
 [Drink, Eat],
 [Drink, Sleep],
 [Drink, Drink]]

现在,我有一个比三个动作大得多的列表,N 可能是 3 或更多。

我将如何在 Python 2.7 中执行此操作?

4

2 回答 2

5

听起来你想要一个列表的笛卡尔积本身。使用itertools.product()

>>> import itertools, pprint
>>> mylist = ["Eat","Sleep","Drink"]
>>> my_combination = list(itertools.product(mylist, repeat = 2))
>>> pprint.pprint (my_combination)
[('Eat', 'Eat'),
 ('Eat', 'Sleep'),
 ('Eat', 'Drink'),
 ('Sleep', 'Eat'),
 ('Sleep', 'Sleep'),
 ('Sleep', 'Drink'),
 ('Drink', 'Eat'),
 ('Drink', 'Sleep'),
 ('Drink', 'Drink')]

可选repeat参数控制列表的“深度”。

请注意,列表的大小会随着深度呈指数增长N。不要一次实现整个列表 - 相反,一次使用一个元素。

# Don't do this - will crash Python with out-of-memory error
list(itertools.product(my_list, repeat = 100000))

# Iterate over the list instead
for one_combination in itertools.product(my_list, repeat = 100000):
    print (one_combination)
于 2012-05-17T05:29:19.167 回答
1
>>> import itertools
>>> actions='eat','sleep','drink'
>>> mylist=[]
>>> [mylist.append(list(i)) for i in list(itertools.product(actions,repeat=2))]
[None,None, None, None, None, None, None, None, None]
>>> mylist
[['eat', 'eat'], ['eat', 'sleep'], ['eat', 'drink'], ['sleep', 'eat'], ['sleep', 'sleep'],   ['sleep', 'drink'], ['drink', 'eat'], ['drink', 'sleep'], ['drink', 'drink']]
于 2012-05-17T05:59:24.083 回答