user2837332
user2837332

Reputation: 85

Doing calculation in Tuples on List Comprehension

I am new to list comprehension, and I'd like to do something with tuples. So this is the problem:

Given two vectors l1 and l2, I wish to combine them into tuples. Then I'd like to multiply them before summing all of them up.

So for example, if i have l1 = [1,2,3] and l2 = [4,5,6], I'd like to combine them with zip function into [(1,4),(2,5),(3,6)].

After this, I want to multiply and add 1 to the tuples. So it will be [(1*4)+1,(2*5)+1,(3*5)+1], giving [4,11,16]

After that I want to sum the list up into 4+11+16 which should give 31.

I've learnttuple(map(operator.add, a, b)) before which can add up the tupples. But since now I need to do one more calculation, I have no idea how to get started. It will be good if it can be done in a single line with list comprehension. Anyone got an idea?

Upvotes: 0

Views: 105

Answers (4)

heemayl
heemayl

Reputation: 42007

Try this :

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> sum([(i*j)+1 for (i, j) in zip(l1, l2)])
35

Upvotes: 0

implementation with map

def f(xs, ys, k=1):
    """
    xs : first list
    ys : second list
    k  : sum constant -- problem case = 1
    """
    return sum(map(lambda x, y: x*y + k, xs, ys))

print f([1,2,3],[4,5,6], 1) == 35

Upvotes: 0

Dan D.
Dan D.

Reputation: 74645

Consider:

sum(a * b + 1 for a, b in zip(l1, l2))

See that:

>>> l1 = [1,2,3]; l2 = [4,5,6]
>>> sum(a * b + 1 for a, b in zip(l1, l2))
35

Upvotes: 3

TerryA
TerryA

Reputation: 59974

I think your calculations are a little off but you want this?

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = zip(l1, l2)
>>> l3
[(1, 4), (2, 5), (3, 6)]
>>> l4 = [i*j for i, j in l3]
>>> l4
[4, 10, 18]
>>> l5 = [x+1 for x in l4]
>>> l5
[5, 11, 19]
>>> sum(l5)
35

Upvotes: 0

Related Questions