我正在尝试找出一种方法,以给定一个充满整数的列表以及每个元素的逆数来生成列表中元素的所有可能组合。
我尝试生成此列表的所有可能排列,然后通过执行0-element使其元素之一为逆,但这不是我想要的。
type Person struct {
Name Name
Age int
Address Address
Phone string
}
例如,给定列表[1、2、3、4、5],我想返回(或简单地打印)以下所有列表:
def permutation(a_list):
#if the list is empty then there are no permutations
if len(a_list) == 0:
return 0
# if there is only 1 element, then only 1 permutation possible
if len(a_list) == 1:
ret = []
ret.append([a_list[0]])
ret.append([-a_list[0]])
return ret
temp_list = []
# iterate the input list and calculate the permutation
for i in range (0, len(a_list)):
if a_list[i].isnumeric():
val = int(a_list[i])
# ~n = -n -1
#val = ~val + 1
val = 0 - val
rem_list = a_list[:i] + a_list[i+1:]
else:
print("not numeric value")
break
# generate all permutations where val is the first element
for p in permutation(rem_list):
temp_list.append([val] + list(p))
return temp_list
#driver
data = list('12345')
for p in permutation(data):
print(p)
答案 0 :(得分:1)
import itertools
a = [1,2,3,4]
list(itertools.product(*[[x, -x] for x in a]))
[(1, 2, 3, 4), (1, 2, 3, -4), (1, 2, -3, 4), (1, 2, -3, -4), (1, -2, 3, 4), (1, -2, 3, -4), (1, -2, -3, 4), (1, -2, -3, -4), (-1, 2, 3, 4), (-1, 2, 3, -4), (-1, 2, -3, 4), (-1, 2, -3, -4), (-1, -2, 3, 4), (-1, -2, 3, -4), (-1, -2, -3, 4), (-1, -2, -3, -4)]
答案 1 :(得分:1)
列出“ inverse”和zip以获得对,并使用itertools product。
from itertools import product
lst = [1, 2, 3, 4]
inverse_lst = [-x for x in lst]
result = list(product(*zip(lst, inverse_lst)))
print(result)
[(1, 2, 3, 4),
(1, 2, 3, -4),
(1, 2, -3, 4),
(1, 2, -3, -4),
(1, -2, 3, 4),
(1, -2, 3, -4),
(1, -2, -3, 4),
(1, -2, -3, -4),
(-1, 2, 3, 4),
(-1, 2, 3, -4),
(-1, 2, -3, 4),
(-1, 2, -3, -4),
(-1, -2, 3, 4),
(-1, -2, 3, -4),
(-1, -2, -3, 4),
(-1, -2, -3, -4)]