可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm trying to make a function in Python that takes a list of integers as input and returns a greater list containing all positive and negative possibilities of those numbers.
Pretend '+' is a positive number and '-' is a negative number
The output should match up with:
foo([-4]) >>> [ [4], [-4] ] foo([+, +]) >>> [ [+,+], [+,-], [-,+], [-,-] ] foo([-, +]) >>> [ [+,+], [+,-], [-,+], [-,-] ] foo([-1, 3]) >>> [ [1,3], [1,-3], [-1,3], [-1,-3] ] foo( [+,-,+] ) >>> [ [-,-,-],[+,-,-],[-,+,-],[-,-,+],[+,+,-],[+,-,+],[-,+,+],[+,+,+] ]
回答1:
For just numbers, you can use itertools.product
to create all combos, after generating a list with both positive and negative numbers:
from itertools import product def foo(nums): return list(product(*((x, -x) for x in nums)))
Demo:
>>> foo([-4]) [(4,), (-4,)] >>> foo([-1, 3]) [(1, 3), (1, -3), (-1, 3), (-1, -3)] >>> foo([1, 3]) [(1, 3), (1, -3), (-1, 3), (-1, -3)] >>> foo([1, -3, 4]) [(1, 3, 4), (1, 3, -4), (1, -3, 4), (1, -3, -4), (-1, 3, 4), (-1, 3, -4), (-1, -3, 4), (-1, -3, -4)]
回答2:
list(itertools.product(*([x, -x] for x in input)))
You want every possible way to pick either a number or its negative, for each number in the input. That's the Cartesian product of {x[i], -x[i]}
for each x[i]
in the input. itertools.product
can do that for you, and then list
makes a list of all the output.
回答3:
You can use itetools.product
, find the cartesian product of [1, -1]
depending on the length of the input list and then multiple them with the items in the input list.
>>> from operator import mul >>> from itertools import product def solve(lis): for prod in product([-1, 1], repeat=len(lis)): yield [mul(*x) for x in zip(prod, lis)] ... >>> list(solve([-4])) [[4], [-4]] >>> list(solve([-1, 3])) [[1, -3], [1, 3], [-1, -3], [-1, 3]]