开发者

Python trim last and sort list

开发者 https://www.devze.com 2023-01-16 01:43 出处:网络
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\', \

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 nu开发者_Go百科mber

map(fn, MC)

How do I remove B, M with fn, and sort list mc high to low.


  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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号