首页 > 解决方案 > Sort double dimensions list with a given column Python

问题描述

I've started Python recently and came up with a project that gives me a 2 dimensions list.

list = [
    ['Symbol', 'Price', 'Number', 'Currency'],
    ['MSFT', '100', '25', 'USD'],
    ['AAPL', '200', '10', 'USD'],
    ['TSLA', '245', '30', 'USD']
]

And I want to sort it by the column Number. I found a way, but it involves three loops to print it. (I looked but couldn't find an answer to my question. Sorry if it already exists)

final_list = [] # To store the ordered items
list_of_numbers = [] # To get the list of item[2]

for item in list: # For every row in the list
    if item[2] != "Number": # To not take into account the first line
        list_of_numbers.append(int(item[2])) # Add the number to the list

list_of_numbers.sort() # Sort the list of numbers

for i in range(1, len(list)): # To get through every row, without the first
    index = list_of_numbers[i-1] # To find each number of the list_of_numbers
    for item in list:
        if item[2] == "Number": # Not the first row
            pass
        elif int(item[2]) == index:
            final_list.append(item) # Add the row in the numeric order
            break

for item in final_list:
    print(item)

The output is the following, and what I want:

['AAPL', '200', '10', 'USD']
['MSFT', '100', '25', 'USD']
['TSLA', '245', '30', 'USD']

But, I really think it's not optimum. Would their be a way to do the same in a more efficient way ?

Thanks a lot and have a nice day.

标签: python

解决方案


这是一个简单的方法:

>>> list = [
...     ['Symbol', 'Price', 'Number', 'Currency'],
...     ['MSFT', '100', '25', 'USD'],
...     ['AAPL', '200', '10', 'USD'],
...     ['TSLA', '245', '30', 'USD']
... ]

>>> sorted(list[1:], key=lambda x: x[2])
>>>[['AAPL', '200', '10', 'USD'], ['MSFT', '100', '25', 'USD'], ['TSLA', '245', '30', 'USD']]

推荐阅读