从两个列表构建元组列表

时间:2013-01-09 09:36:46

标签: python list tuples cartesian-product

我写了这个函数:

def buildAllPairs(l1, l2):
      l=[]
      for s in l1:
          for p in l2:
               l.append((s, p))
      return l

但它只在我使用列表中的数字时才有效,因为字母表出现了NameError,有人可以告诉我为什么会这样吗?

1 个答案:

答案 0 :(得分:4)

使用itertools.product功能:

>>> import itertools
>>> list(itertools.product([1, 'a'], [2, 'b']))
[(1, 2), (1, 'b'), ('a', 2), ('a', 'b')]

请注意,itertools.product()本身会返回一个itertools.product对象,实际上是一个生成器,而不是列表。

相关问题