python - 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.
解决方案
这是一个简单的方法:
>>> 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']]
推荐阅读
- java - 如何在 java 中从 10-JUN-02 01.57.07.848594000 PM 转换为 yyyy-MM-dd-HH24.MI.SS.FF6
- multithreading - 通过多线程完成的应用程序对执行时间的改进受到物理内核数量的限制?
- crystal-reports - Crystal Reports,将子报表链接到日期组
- mysql - MySQL表注释跨越多行
- java - 无法在 intellij 中导入 JavaFx
- python - 并发和 Selenium - 多处理与多线程
- docker - 无法启动 docker 守护进程(graphdriver 问题)
- python - MinMaxScaling 没有返回正确的值
- objective-c - 我有一个带有自定义 UIStoryboardSegue 对象的小型测试项目,但动画有黑色阴影。有什么办法可以去掉?
- angular6 - 是否可以将 angular-6 生成的库导入 angular 5?