orllais
orllais

Reputation: 17

How to multiply a number by the second value in a list of tuples (python)?

I have a list of tuples that my program read from a document that begins like so:

(1914, 1.0)
(1915, 1.0)
(1916, 7.9)
(1917, 17.4)
(1918, 18.0)

What I'm trying to do is take the second number (the float) and multiply it by another number determined by the user. For example, if the user chose 14.4, the program would multiply 14.4*1.0, 14.4*1.0, 14.4*7.9, 14.4*17.4, 14.4*18.0 and so on and append it to a list. I've tried

[x*14.4 for x in t2[1]]

Where t2 is the tuple, but obviously this doesn't work and gives the TypeError "'float' object not iterable." I'm very new to python and I'm not entirely sure what to do instead.

Upvotes: 0

Views: 2502

Answers (4)

SkyLeach
SkyLeach

Reputation: 1482

#!/usr/bin/env python3
import sys
mytup = (
    (1914, 1.0),
    (1915, 1.0),
    (1916, 7.9),
    (1917, 17.4),
    (1918, 18.0)
)
x = int(sys.argv[1])
print(['%0.2f' % (b*x) for a, b in mytup])

results in:

['3.00', '3.00', '23.70', '52.20', '54.00']

Basically that's just a closure/anon func to consume the default generator+iterator which I'm assuming is what you want after reading your question.

Upvotes: 0

dawg
dawg

Reputation: 103998

Given:

LoT=[(1914, 1.0),
(1915, 1.0),
(1916, 7.9),
(1917, 17.4),
(1918, 18.0)]

Since tuples are immutable, you need to create a new tuple (if you want a new list of tuples).

>>> x=14.4
>>> [(t[0], t[1]*x) for t in LoT]
[(1914, 14.4), (1915, 14.4), (1916, 113.76), (1917, 250.55999999999997), (1918, 259.2)]

If you want just a list of the second element of the tuple multiplied, you can do:

>>> [t[1]*x for t in LoT]
[14.4, 14.4, 113.76, 250.55999999999997, 259.2]

You post states:

What I'm trying to do is take the second number (the float) and multiply it by another number determined by the user.

That is why I used [t[1]*x for t in LoT] because t[1] is the second element of any tuple with at least 2 elements.

If every tuple is guaranteed to be two elements long, you can also do [y*x for _, y in LoT] for the same list.

Upvotes: 2

Delgan
Delgan

Reputation: 19677

What about:

[y * 14.4 for x, y in tuples]

Upvotes: 1

wvdz
wvdz

Reputation: 16651

Try this:

[x[1]*14.4 for x in t2]

Upvotes: 0

Related Questions