听起来你想要一个列表的笛卡尔积本身。使用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)