Python sorted list float

Sort a list of numeric strings in Python

In Python, you can sort a list with the sort() method or the sorted() function.

This article describes how to sort a list of numeric strings not filled with zeros.

  • sort() and sorted()
  • Notes on numeric strings not filled with zeros
  • Specify int() or float() for the key parameter
  • Extract numbers in strings with regular expressions
    • Only one number in a string
    • More than one number in a string
    • Some elements have no number in a string

    sort() and sorted()

    sort() is a method of a list, which sorts the original list itself.

    l = [10, 1, 5] l.sort() print(l) # [1, 5, 10] 

    sorted() is a built-in function that creates a new sorted list. The original list is not changed.

    l = [10, 1, 5] print(sorted(l)) # [1, 5, 10] print(l) # [10, 1, 5] 

    By default, sorting is done in ascending order. If you want to sort in descending order, set the reverse parameter to True . The example uses sorted() , but you can also use sort() .

    print(sorted(l, reverse=True)) # [10, 5, 1] 

    For more information, including how to sort tuples and strings, see the following article.

    Notes on numeric strings not filled with zeros

    In the case of a list of numeric strings filled with zeros, it is sorted without any problem. Note that the following sample code uses sorted() , but the same applies to sort() .

    l = ['10', '01', '05'] print(sorted(l)) # ['01', '05', '10'] 

    In the case of a list of numeric strings not filled with zeros, the strings are sorted in the dictionary order, not as numbers. For example, ’10’ is considered smaller than ‘5’ .

    l = ['10', '1', '5'] print(sorted(l)) # ['1', '10', '5'] 

    Specify int() or float() for the key parameter

    sort() and sorted() have the key parameter.

    By specifying int() or float() , which converts a string to a number, for the key parameter, a list of numeric strings is sorted as numbers, not as strings.

    When a function is specified as an argument, () is unnecessary.

    l = ['10', '1', '5'] print(sorted(l, key=int)) # ['1', '5', '10'] print(sorted(l, key=float)) # ['1', '5', '10'] 

    Integer strings can be converted with either int() or float() , but decimals must be converted with float() .

    l = ['10.0', '1.0', '5.0'] print(sorted(l, key=float)) # ['1.0', '5.0', '10.0'] 

    The sort() has the key parameter as well.

    l = ['10', '1', '5'] l.sort(key=int) print(l) # ['1', '5', '10'] 

    As you can see from the results so far, the function specified for key is only applied for comparison, and the result remains the original.

    If you want the result in int or float , just sort the converted list using list comprehensions.

    l = ['10', '1', '5'] print([int(s) for s in l]) # [10, 1, 5] print(sorted([int(s) for s in l])) # [1, 5, 10] 

    Extract numbers in strings with regular expressions

    For numeric strings, you need only specify int() or float() for key .

    However, for strings with embedded numbers, you must use the regular expression module re to extract the numeric part of the string.

    l = ['file10.txt', 'file1.txt', 'file5.txt'] 

    Only one number in a string

    Get a match object by search() and take the matched part as a string with the group() method.

    Use \d+ as a regular expression pattern. \d is a number, + is a repetition of one or more characters, and \d+ matches a sequence of one or more numbers.

    import re s = 'file5.txt' print(re.search(r'\d+', s).group()) # 5 

    This sample code uses a raw string.

    Since a string is returned, use int() or float() to convert it to a number.

    print(type(re.search(r'\d+', s).group())) # print(type(int(re.search(r'\d+', s).group()))) # 

    With a lambda expression, you can specify this process for the key parameter of sort() or sorted() .

    l = ['file10.txt', 'file1.txt', 'file5.txt'] print(sorted(l)) # ['file1.txt', 'file10.txt', 'file5.txt'] print(sorted(l, key=lambda s: int(re.search(r'\d+', s).group()))) # ['file1.txt', 'file5.txt', 'file10.txt'] 

    If the number of elements is small, you do not have to worry too much, but it is more efficient to generate a regular expression object with compile() and use it.

    p = re.compile(r'\d+') print(sorted(l, key=lambda s: int(p.search(s).group()))) # ['file1.txt', 'file5.txt', 'file10.txt'] 

    More than one number in a string

    search() returns only the first match.

    s = '100file5.txt' print(re.search(r'\d+', s).group()) # 100 

    findall() returns all matching parts as a list.

    print(re.findall(r'\d+', s)) # ['100', '5'] print(re.findall(r'\d+', s)[1]) # 5 

    If you enclose parts of a pattern in () , you can extract only that part with the groups() method.

    For example, the file(\d+) pattern extracts » from ‘file’ . Note that it returns a tuple even if there is only one corresponding part.

    print(re.search(r'file(\d+)', s).groups()) # ('5',) print(re.search(r'file(\d+)', s).groups()[0]) # 5 
    print(re.search(r'(\d+)\.', s).groups()[0]) # 5 
    l = ['100file10.txt', '100file1.txt', '100file5.txt'] print(sorted(l, key=lambda s: int(re.findall(r'\d+', s)[1]))) # ['100file1.txt', '100file5.txt', '100file10.txt'] print(sorted(l, key=lambda s: int(re.search(r'file(\d+)', s).groups()[0]))) # ['100file1.txt', '100file5.txt', '100file10.txt'] print(sorted(l, key=lambda s: int(re.search(r'(\d+)\.', s).groups()[0]))) # ['100file1.txt', '100file5.txt', '100file10.txt'] 
    p = re.compile(r'file(\d+)') print(sorted(l, key=lambda s: int(p.search(s).groups()[0]))) # ['100file1.txt', '100file5.txt', '100file10.txt'] 

    Some elements have no number in a string

    If the strings of all elements contain numbers, there is no problem, but if not, you should consider the case of no match.

    l = ['file10.txt', 'file1.txt', 'file5.txt', 'file.txt'] # print(sorted(l, key=lambda s:int(re.search(r'\d+', s).group()))) # AttributeError: 'NoneType' object has no attribute 'group' 

    For example, define the following function. The first parameter is a string, the second is a regular expression object, and the third is the return value if it does not match.

    def extract_num(s, p, ret=0): search = p.search(s) if search: return int(search.groups()[0]) else: return ret 

    The result is as follows. The pattern needs () because it uses groups() .

    p = re.compile(r'(\d+)') print(extract_num('file10.txt', p)) # 10 print(extract_num('file.txt', p)) # 0 print(extract_num('file.txt', p, 100)) # 100 

    The third argument is optional.

    You can specify this function for the key parameter of sort() or sorted() .

    print(sorted(l, key=lambda s: extract_num(s, p))) # ['file.txt', 'file1.txt', 'file5.txt', 'file10.txt'] print(sorted(l, key=lambda s: extract_num(s, p, float('inf')))) # ['file1.txt', 'file5.txt', 'file10.txt', 'file.txt'] 

    If you want to put elements that do not contain numerical values at the end of the ascending order, you can use the infinity inf .

    If a string contains more than one number, change the regular expression object.

    l = ['100file10.txt', '100file1.txt', '100file5.txt', '100file.txt'] p = re.compile(r'file(\d+)') print(sorted(l, key=lambda s: extract_num(s, p))) # ['100file.txt', '100file1.txt', '100file5.txt', '100file10.txt'] print(sorted(l, key=lambda s: extract_num(s, p, float('inf')))) # ['100file1.txt', '100file5.txt', '100file10.txt', '100file.txt'] 

    Источник

    Sort List of Floats in Python (2 Examples)

    TikTok Icon Statistics Globe

    In this tutorial you’ll learn how to sort a list of floats in Python programming.

    The table of content is structured as follows:

    Sound good? Let’s dive into it!

    Exemplifying Data

    Let’s first construct some example data to illustrate how to sort a list of float numbers in Python.

    float_list = [1.5, 3.3, -0.87, 15.99, -3.0, 0] # generating an example float list

    As seen float_list contains six float numbers as you can understand from the decimal points.

    Example 1: Sorting with sort() Method

    This example demonstrates how to use the sort() method for sorting a list of floats in ascending and descending order.

    float_list.sort() # sorting the list ascending print(float_list) # printing the sorted list # [-3.0, -0.87, 0, 1.5, 3.3, 15.99]

    When the reverse parameters are set to ‘True’, then the list will be sorted in a descending way.

    float_list.sort(reverse=True) # sorting the list descending print(float_list) # printing the sorted list # [15.99, 3.3, 1.5, 0, -0.87, -3.0]

    You can see how the first element (-0.3) and last element (15.99) in float_list in ascending order are now placed in the last and first positions in float_list in descending order.

    Example 2: Sorting using sorted() Function

    In this example, the sorting will be done with the sorted() function.

    print(sorted(float_list)) # sorting the list and printing # [-3.0, -0.87, 0, 1.5, 3.3, 15.99]

    The difference between the sort() method and the sorted() function is that sort() method doesn’t generate a new list. The sort() method transforms the list into the sorted version, however, the sorted() function returns a new list with the same elements but sorted. This means that the sorted() function doesn’t alter the original list.

    See how float_list still takes the same initial values by printing it.

    print(float_list) # printing float_list # [1.5, 3.3, -0.87, 15.99, -3.0, 0]

    Once again if the reverse parameter is set to True then the sorting will be in a descending way.

    print(sorted(float_list, reverse=True)) # sorting in reverse and printing # [15.99, 3.3, 1.5, 0, -0.87, -3.0]

    You can compare and see that the same results were obtained with Example 1.

    Video & Further Resources

    Do you need further information on the topics of this page? Then I recommend having a look at the following video on my YouTube channel. I’m demonstrating the contents of this tutorial in the video.

    The YouTube video will be added soon.

    In addition, you could read the other articles on this homepage:

    Summary: This article has demonstrated how to create a sorted list of floats in Python in Python. Please let me know in the comments section if you have any additional questions or comments. Furthermore, please subscribe to my email newsletter for updates on new tutorials.

    Ömer Ekiz Python Programming & Informatics

    This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

    Источник

    Читайте также:  Php get referer url
Оцените статью