有谁知道如何使用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
吗?
谢谢!
答案 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
解决方案:
您可以使用nested
和for-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']