python - 如何使用 Python 中的列表生成所有可能的排列对?

标签 python python-3.x

<分区>

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

例子:

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

最佳答案

您可以使用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']

关于python - 如何使用 Python 中的列表生成所有可能的排列对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697775/

相关文章:

python - 需要减少基于公式和数字 n 创建数字列表的运行时间

python - 了解 time.perf_counter() 和 time.process_time()

python-3.x - 在 python 3 中请求 HTTP/2 切换协议(protocol)

python - 用 Python 表示网络

python - 如何在python中设置mfrow/mfcol

python - Python 的 MySQL 查询中字符串参数不足,多个 IN 子句包含列表值

python - 线性链 CRF 分类器使用哪个激活函数?

python - 如何禁用输入输入直到双击?

python-3.x - SQlAlchemy __tablename__ NameError

python - 一次从 GridSearch 设置多个参数