如何在一组N-deep对象中创建列表或每个排列

时间:2012-05-17 05:25:09

标签: python list python-2.7

我有一个Action对象元组

我想创建一个列表,列出Action对象N deep的每个可能的排列。

即。如果我有吃,睡,喝的行为,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中执行此操作?

2 个答案:

答案 0 :(得分:5)

听起来你想要列表的Cartesian product。使用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)

答案 1 :(得分: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']]