【问题标题】:Find all products produced by 2 unique elements of an array (python)查找由数组的 2 个唯一元素产生的所有产品(python)
【发布时间】:2013-10-20 21:34:19
【问题描述】:

如何确定python中数组中所有数字的乘积/和/差/除? 例如乘法:

array=[1,2,3,4]

输出将只是 1*2、1*3、1*4、2*3、2*4、3*4:

[2,3,4,6,8,12] 

我了解“for”和“while”循环的工作原理,但无法找出解决方案——如何在 len(array) 变量数组中找到每组唯一的 2 个变量?完成后,我可以做相应的乘法/除法/减法/等。

我最多只能做一个数组的乘积:

array=[1,2,3]
product = 1
for i in array:
    product *= i
print product

【问题讨论】:

    标签: python arrays loops


    【解决方案1】:

    使用itertools.combinations:

    >>> from itertools import combinations
    >>> array = [1, 2, 3, 4]
    >>> [i * j for i, j in combinations(array, 2)]
    [2, 3, 4, 6, 8, 12]
    

    【讨论】:

    • 哈!我的短了 1 行 - LOL ;-)
    • @TimPeters Pfft。我的有链接。菜鸟:)
    • 阅读def组合的代码,我想到的可能性为0
    • @NoobCoder 这就是为什么 itertools 适合你:)
    【解决方案2】:

    给你。当您知道技巧时,这很容易;-)

    >>> from itertools import combinations
    >>> [a*b for a, b in combinations([1,2,3,4], 2)]
    [2, 3, 4, 6, 8, 12]
    

    【讨论】:

    • 遗憾的是,找到所有产品的答案不是itertools.product
    【解决方案3】:
    array = [1, 2, 3, 4]
    

    如果您仍然对基于循环的解决方案感兴趣。

    result = []
    for i in range(len(array)):
        for j in range(i + 1, len(array)):
            result.append(array[i] * array[j])
    print result
    

    这可以用列表推导式来写,像这样

    print [array[i] * array[j] for i in range(len(array)) for j in range(i + 1, len(array))]
    

    【讨论】:

      【解决方案4】:

      使用所有的 ITERTOOLS!

      >>> from itertools import starmap, combinations as combos
      >>> from operator import mul
      >>> products = starmap(mul, combos([1,2,3,4], 2))
      >>> list(products)
      [2, 3, 4, 6, 8, 12]
      

      好吧,不是全部,而是 MOAR。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        相关资源
        最近更新 更多