【问题标题】:Create all possible combinations of a list in Python [duplicate]在Python中创建列表的所有可能组合[重复]
【发布时间】:2017-11-26 17:31:11
【问题描述】:

有人知道如何使用 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 吗? 谢谢!

【问题讨论】:

  • 向我们展示您到目前为止所尝试的内容。
  • 没有@IrmendeJong
  • 请问? StackOverflow 不是代码编写服务。

标签: python python-3.x combinations permutation


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    Python解决方案:

    您可以在 list-comprehensionstring concatenation 中使用 nested for-loops 执行此操作:

    [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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多