代码之家  ›  专栏  ›  技术社区  ›  Luka Rahne

泛函中的向量代数

  •  0
  • Luka Rahne  · 技术社区  · 14 年前


    此代码适用于n<100,但不适用于n>1000

    from itertools import *
    
    #n=10000 # do not try!!!
    n=100
    twin=((i,i**2,i**3) for i in xrange(1,n+1))
    
    def sum(x=0,y=0):
        return x+y
    
    def dubsum(x,y):
        return (reduce(sum,i) for i in izip(x,y) )
    
    print [ i for i in reduce(dubsum,twin) ]
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   Jason Orendorff Oliver    14 年前

    这样地:

    print [sum(e) for e in izip(*twin)]
    

    或者更具功能性:

    print map(sum, izip(*twin))
    

    请注意,压缩非常类似于转置二维数组。

    >>> zip([1, 2, 3, 4],
    ...     [5, 6, 7, 8])  ==  [(1, 5),
    ...                         (2, 6),
    ...                         (3, 7),
    ...                         (4, 8)]
    True
    
        2
  •  0
  •   Tony Veijalainen    14 年前

    Python内置了sum,何必费心:

    from itertools import *
    
    n=10000
    twin=((i,i**2,i**3) for i in xrange(1,n+1))
    x,y,z= izip(*twin)
    
    print sum(x),sum(y),sum(z)