【问题标题】:Python - Permutation/Combination column-wisePython - 按列排列/组合
【发布时间】:2015-09-15 20:47:21
【问题描述】:

我有一个清单

mylist = [
    ['f', 'l', 'a', 'd', 'l', 'f', 'k'], 
    ['g', 'm', 'b', 'b', 'k', 'g', 'l'], 
    ['h', 'n', 'c', 'a', 'm', 'j', 'o'], 
    ['i', 'o', 'd', 'c', 'n', 'i', 'm'],
    ['j', 'p', 'e', 'e', 'o', 'h', 'n'], 
]

我想按列进行排列/组合,这样列的元素被限制在该列中,即 f,g,h,i,j 保留在第 1 列中,l,m,n,o,p 保留在第 2 列等中,在排列/组合的结果中。这如何在 Python 2.7 中实现?

【问题讨论】:

    标签: python python-2.7 combinations permutation itertools


    【解决方案1】:

    您可以use zip(*mylist) 列出mylist 的“列”。然后使用the * operator(再次)将这些列表解压缩为IT.productIT.combinations 的参数。例如,

    import itertools as IT
    list(IT.product(*zip(*mylist)))
    

    产量

    [('f', 'l', 'a', 'd', 'l', 'f', 'k'),
     ('f', 'l', 'a', 'd', 'l', 'f', 'l'),
     ('f', 'l', 'a', 'd', 'l', 'f', 'o'),
     ('f', 'l', 'a', 'd', 'l', 'f', 'm'),
     ...]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2013-02-03
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多