在Python中创建列表的所有可能组合

时间:2017-11-26 17:31:12

标签: python python-3.x combinations permutation

有谁知道如何使用Python 3找出给定列表的所有可能组合?

我的列表如下所示:

usersArray = ["John", "Mike", "Robert", "Tom"]
foodsArray = ["hamburger", "cake", "cheese"]

我想有这样的事情:

Johnhamburger
Mikehamburger
Roberthamburger
Tomhamburger

Johncake
Mikecake
Robertcake
Tomcake

Johncheese
Mikecheese
Robertcheese
Tomcheese

#and then the opposite

hamburgerJohn
hamburgerMike
hamburgerRobert
hamburgerTom

cakeJohn
...
...
...

cheeseJohn
...
...
...

我可以使用itertools吗? 谢谢!

2 个答案:

答案 0 :(得分:2)

这只是itertools产品的两种用途:

for food, user in itertools.product(foodsArray, usersArray):
    print(user+food)

for food, user in itertools.product(foodsArray, usersArray):
    print(food+user)

答案 1 :(得分:1)

Python解决方案:

您可以使用nestedfor-loops list-comprehension中的string concatenation来执行此操作:

[u + f for u in usersArray for f in foodsArray]

给出:

['Johnhamburger', 'Johncake', 'Johncheese', 'Mikehamburger', 'Mikecake', 'Mikecheese', 'Roberthamburger', 'Robertcake', 'Robertcheese', 'Tomhamburger', 'Tomcake', 'Tomcheese']
[f + u for u in usersArray for f in foodsArray]

给出:

['hamburgerJohn', 'cakeJohn', 'cheeseJohn', 'hamburgerMike', 'cakeMike', 'cheeseMike', 'hamburgerRobert', 'cakeRobert', 'cheeseRobert', 'hamburgerTom', 'cakeTom', 'cheeseTom']