Home > database >  How can I sort a list that has a float in string format with a non-numeric value?
How can I sort a list that has a float in string format with a non-numeric value?

Time:04-25

I have a list like this

data = [('£3.46', 'I001'), ('£10.46', 'I002')] 

I want to sort this list with

data.sort()

however the sorted list puts £10.46 before £3.46, I'm assuming this is because the data is a string and £1 comes before £3.
I have tried looking at lambda functions but I can't get my head around it.

CodePudding user response:

One option is to strip "£" and convert the number to float as a sorting key:

data.sort(key=lambda x: float(x[0].lstrip('£')))
print(data)

Output:

[('£3.46', 'I001'), ('£10.46', 'I002')]

CodePudding user response:

This is a general approach with some limitations, but should work in a wide variety of similar situations.

import re

def float_then_text(values):
    '''Yield (float, str, float, str, ...) for (str, str, ...)'''
    for text in values:
        try:
            yield float(re.sub(r'[^\d.] ', '', text))
        except ValueError:
            yield None
        yield text

data = [('£3.46', 'I001'), ('£10.46', 'I002')]

data.sort(key=lambda i: list(float_then_text(i)))

The function float_then_text will convert from ('£3.46', 'I001') to (3.46, '£3.46', 1.0, 'I001') and so on.

Setting key=lambda i: list(float_then_text(i)) tells sort() that you want to run list(float_then_text(i)) on every element i of data before sorting it. The key argument only affects the sorting order.

  • Related