如何从Python中的列表生成所有可能的对排列?
示例:
input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
答案 0 :(得分:3)
您可以使用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']
答案 1 :(得分:3)
只需将您的列表提供给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
作为变量名称,因为它会覆盖交互式文本输入功能。
答案 2 :(得分:0)
使用itertools.permutations
:
from itertools import permutations
input = [3, 8, 2]
output = map('-'.join, permutations(map(str, input), 2))
答案 3 :(得分:0)
您可以尝试使用itertools:
数据是:
https://api.deepl.com/v1/translate?text=Hello%20World!&target_lang=EN&auth_key=XXX
一线解决方案:
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)