Multiply Adjacent Elements

◇◆丶佛笑我妖孽 提交于 2019-12-10 21:19:12

问题


I have a tuple of integers such as (1, 2, 3, 4, 5) and I want to produce the tuple (1*2, 2*3, 3*4, 4*5) by multiplying adjacent elements. Is it possible to do this with a one-liner?


回答1:


Short and sweet. Remember that zip only runs as long as the shortest input.

print tuple(x*y for x,y in zip(t,t[1:]))



回答2:


>>> t = (1, 2, 3, 4, 5)
>>> print tuple(t[i]*t[i+1] for i in range(len(t)-1))
(2, 6, 12, 20)

Not the most pythonic of solutions though.




回答3:


If t is your tuple:

>>> tuple(t[x]*t[x+1] for x in range(len(t)-1))
(2, 6, 12, 20)

And another solution with lovely map:

>>> tuple(map(lambda x,y:x*y, t[1:], t[:-1]))
(2, 6, 12, 20)

Edit: And if you worry about the extra memory consuption of the slices, you can use islice from itertools, which will iterate over your tuple(thx @eyquem):

>>> tuple(map(lambda x,y:x*y, islice(t, 1, None), islice(t, 0, len(t)-1)))
(2, 6, 12, 20)



回答4:


tu = (1, 2, 3, 4, 5)

it = iter(tu).next
it()
print tuple(a*it() for a in tu)

I timed various code:

from random import choice
from time import clock
from itertools import izip

tu = tuple(choice(range(0,87)) for i in xrange(2000))

A,B,C,D = [],[],[],[]

for n in xrange(50):

    rentime = 100

    te = clock()
    for ren in xrange(rentime): # indexing
        tuple(tu[x]*tu[x+1] for x in range(len(tu)-1))
    A.append(clock()-te)

    te = clock()
    for ren in xrange(rentime): # zip
        tuple(x*y for x,y in zip(tu,tu[1:]))
    B.append(clock()-te)

    te = clock()
    for ren in xrange(rentime): #i ter
        it = iter(tu).next
        it()
        tuple(a*it() for a in tu)
    C.append(clock()-te)

    te = clock()
    for ren in xrange(rentime): # izip
        tuple(x*y for x,y in izip(tu,tu[1:]))
    D.append(clock()-te)


print 'indexing ',min(A)
print 'zip      ',min(B)
print 'iter     ',min(C)
print 'izip     ',min(D)

result

indexing  0.135054036197
zip       0.134594201218
iter      0.100380634969
izip      0.0923947037962

izip is better than zip : - 31 %

My solution isn't so bad (I didn't think so by the way): -25 % relatively to zip, 10 % more time than champion izip

I'm surprised that indexing isn't faster than zip : nneonneo is right, zip is acceptable




回答5:


I like the recipes from itertools:

from itertools import izip, tee

def pairwise(iterable):
    xs, ys = tee(iterable)
    next(ys)
    return izip(xs, ys)

print [a * b for a, b in pairwise(range(10))]

Result:

[0, 2, 6, 12, 20, 30, 42, 56, 72]


来源:https://stackoverflow.com/questions/14916957/multiply-adjacent-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!