Reputation: 25669
I have list MC below:
MC = [('GGP', '4.653B'), ('JPM', '157.7B'), ('AIG', '24.316B'), ('RX', 'N/A'), ('PFE', '136.6B'), ('GGP', '4.653B'), ('MNKD', '672.3M'), ('ECLP', 'N/A'), ('WYE', 'N/A')]
def fn(number):
divisors = {'B': 1, 'M': 1000}
if number[-1] in divisors:
return ((float(number[:-1]) / divisors[number[-1]])
return number
map(fn, MC)
How do I remove B, M with fn, and sort list mc high to low.
Upvotes: 0
Views: 773
Reputation: 71044
def fn(tup):
number = tup[1]
divisors = {'B': 1, 'M': 1000}
if number[-1] in divisors:
return (tup[0], float(number[:-1]) / divisors[number[-1]])
else:
return tup
The problem is that that function was meant to run on a string representation of a number but you were passing it a tuple. So just pull the 1'st element of the tuple. Then return a tuple consisting of the 0'th element and the transformed 1'st element if the 1'st element is transformable or just return the tuple.
Also, I stuck an else clause in there because I find them more readable. I don't know which is more efficient.
as far as sorting goes, use sorted
with a key
keyword argument
either:
MC = sorted(map(fn, MC), key=lambda x: x[0])
to sort by ticker or
MC = sorted(map(fn, MC), key=lambda x: x[1] )
to sort by price. Just pass reversed=True
to the reversed
if you want it high to low:
MC = sorted(map(fn, MC), key=lambda x: x[1], reversed=True)
you can find other nifty sorting tips here: http://wiki.python.org/moin/HowTo/Sorting/
Upvotes: 1