python正数和负数列表的可能性 [英] python positive and negative number list possibilities
本文介绍了python正数和负数列表的可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试在Python中创建一个函数,该函数将整数列表作为输入,并返回包含这些数字的所有正负可能性的更大列表.
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( [+,-,+] )
>>> [ [-,-,-],[+,-,-],[-,+,-],[-,-,+],[+,+,-],[+,-,+],[-,+,+],[+,+,+] ]
推荐答案
对于数字,您可以在生成包含正数和负数的列表后,使用itertools.product
创建所有组合:
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)))
演示:
>>> 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)]
这篇关于python正数和负数列表的可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文