【问题标题】:Function that takes 3 list arguments and returns all the combinations [duplicate]接受3个列表参数并返回所有组合的函数[重复]
【发布时间】:2013-08-09 19:23:14
【问题描述】:

我需要帮助在 Python 中提出一个函数,该函数接受 3 个参数,这些参数是列表并且可以返回所有组合。

例如,如果我跑:

shirts = ['white', 'blue']
ties = ['purple', 'yellow']
suits = ['grey', 'blue']
combinations = dress_me(shirts, ties, suits)
for combo in combinations:
    print combo

它会打印如下内容:

('white', 'purple', 'grey')
('white', 'purple', 'blue')
('white', 'yellow', 'grey')
('white', 'yellow', 'blue')
('blue', 'purple', 'grey')
('blue', 'purple', 'blue')
('blue', 'yellow', 'grey')
('blue', 'yellow', 'blue')

【问题讨论】:

  • 我觉得我的回答是对的。
  • 欢迎来到 Stack Overflow。请尽快阅读About 页面。一般来说,避免试图在标题中写下你的整个问题。
  • @Jonathan:我讨厌有些书呆子会否决这篇文章,我的意思是这个人是新人,让他休息一下——不,你必须阅读 40 页的 EULA,然后在这里发帖。
  • 没有人反对它,尽管它实际上是应得的。 OP刚刚发布了同样的问题。我和其他一些人已经回答了。如果他对答案不满意。他可能会编辑。@MotiurRahman

标签: python function


【解决方案1】:

itertools 来救援。

import itertools

def dress_me(*choices):
  return itertools.product(*choices)

【讨论】:

    【解决方案2】:
    def dress_me(l1, l2, l3):
        return [(i, j, k) for i in l1 for j in l2 for k in l3]
    

    【讨论】:

      【解决方案3】:
      def dress_me(l1, l2, l3):
          res = []
          for i in l1:
              for j in l2:
                  for k in l3:
                      res.append((i, j, k))
          return res
      
      shirts = ['white', 'blue']
      ties = ['purple', 'yellow']
      suits = ['grey', 'blue']
      
      if __name__ == '__main__':  
          combinations = dress_me(shirts, ties, suits)
          for combo in combinations:
              print(combo)
      

      【讨论】:

      • 非常感谢!这真的很有帮助
      猜你喜欢
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      相关资源
      最近更新 更多