【问题标题】:How to generate all possible pairs with permutations from list in Python? [duplicate]如何从Python中的列表中生成所有可能的排列对? [复制]
【发布时间】:2018-05-21 17:17:40
【问题描述】:

如何从 Python 中的列表生成所有可能的对排列?

例子:

input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

【问题讨论】:

  • 欢迎来到 SO。这不是免费的代码编写服务,因此您的问题应该是您自己的尝试。此外,这个问题是重复的。

标签: python python-3.x


【解决方案1】:

你可以使用itertools.permutations:

import itertools
input = [3, 8, 2]
final_list = ["{}-{}".format(*i) for i in itertools.permutations(input, 2)]

输出:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

但是,如果您希望所有操作都达到并包括列表的长度,您可以试试这个:

final_list = list(itertools.chain(*[['-'.join(["{}"]*b).format(*i) for i in itertools.permutations(input, b)] for b in range(2, len(input)+1)]))

输出:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8', '3-8-2', '3-2-8', '8-3-2', '8-2-3', '2-3-8', '2-8-3']

编辑:对于所有可能的操作数:

import re
def tokenize(s):
   converter = {"-":lambda x, y:x-y, '+':lambda x, y:x+y}
   total = 0
   stack = re.findall('\d+|[\-\+]', s)
   operator = None
   for i in stack:
      if i.isdigit():
         if not operator:
            total += int(i)
         else:
            total = converter[operator](total, int(i))
            operator = None
      else:
          operator = i
   return total

new_list = set(list(itertools.chain(*list(itertools.chain(*[[[''.join([''.join('{}'+i) for i in b]+['{}']).format(*c) for b in itertools.permutations(['-', '+'], len(c)-1)] for c in itertools.permutations(input, x)] for x in range(2, len(input)+1)])))))
final_list = {tokenize(a):a for a in new_list}
new_final_list = [b for a, b in final_list.items()]

输出:

['3-2', '8-3', '8-2', '8-3+2', '8-2+3', '8+2', '8+3', '2-8', '3-8', '3+2-8', '2-3']

【讨论】:

  • 很棒的答案,如果我有多个操作数怎么办?
  • @JapexDoe 很高兴为您提供帮助!关于多个操作数,这个答案将在给定列表的情况下找到所有可能的操作。您是指多个列表的输入,目标是找到每个列表的操作吗?
  • 我是 Python 新手,试图理解一些更高级的问题。我的意思是,如果我需要找到给定问题的正负操作数。另外:有没有办法减少列表以删除产生相同结果的所有元素? (2+8 和 8+2 都是 10)。或者不使用排列?我不需要花太多时间在这上面,我可能会自己想办法:)
  • @JapexDoe 请查看我最近的编辑。
  • 谢谢!你真棒! :)
【解决方案2】:

只需将您的列表提供给itertools.permutations 并在列表理解中进行相应的格式化,使用* 运算符直接将tuple 传递给format

import itertools

result = ["{}-{}".format(*x) for x in itertools.permutations([3, 8, 2],2)]

print(result)

结果:

['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

附带说明,不要使用input 作为变量名,因为它会覆盖交互式文本输入功能。

【讨论】:

    【解决方案3】:

    使用itertools.permutations:

    from itertools import permutations
    
    input = [3, 8, 2]
    output = map('-'.join, permutations(map(str, input), 2))
    

    【讨论】:

      【解决方案4】:

      你可以试试itertools:

      数据是:

      input = [3, 8, 2]
      import itertools
      

      一线解决方案:

      print(['{}-{}'.format(i[0],i[1]) for i in itertools.permutations(input,r=2)])
      

      详细解决方案:

      上面的列表理解与:

      final_list=[]
      for i in itertools.permutations(input,r=2):
          final_list.append(('{}-{}'.format(i[0],i[1])))
      print(final_list)
      

      如果你想要减法的结果,那么:

      final_list=[]
      for i in itertools.permutations(input,r=2):
          final_list.append((i[0]-i[1]))
      print(final_list)
      

      【讨论】:

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