tags:

views:

76

answers:

1

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.

+1  A: 
  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/

aaronasterling
its not homework, Im new to python, its better to ask than struggle with python semantics which Im learning
I Seperated to [0], and [1] ran fn on [1] then tried to add back wasnt getting the right ans.
@user428862, how did you separate? did you try the code I've posted? It works for me.
aaronasterling
I wrote comment on first post.
Worked, sorted? high to low?
@user428862 updated. I also included a link to the sorting howto. Struggling is better than asking most of the time. It becomes less of a struggle.
aaronasterling