该程序应该能够对实验进行排序 数据按升序和降序排列。
list=['0.564', '0.787', '1.012', '1.055', '0.656', '0.665', '0.789', '2.110', '2.121', '3.325', '0.025', '3.250', '1.785', '1.998', '1.552', '2.021', '0.998', '1.001', '1.121', '0.564', '0.784', '2.001', '5.454', '5.234', '13.746', '4.785', '3.001', '3.458', '2.987', '3.658', '3.212', '4.165', '4.112', '4.000', '3.589', '3.221', '3.154', '2.118', '2.546', '2.658', '2.131', '1.989', '1.548', '2.112', '1.987', '1.555', '1.197', '1.958', '0.885', '0.847']
我试过了
sorted(list4,key=lambda )
print list4
但是
File "text.py", line 41
sorted(list4,key=lambda )
^
SyntaxError: invalid syntax
(a4-2-225.v276.city.ac.uk)185%
答案 0 :(得分:2)
您可以将sorted
函数与key=float
参数一起使用,将字符串转换为float
进行排序。然后,您可以使用reverse
参数按升序或降序排序。
>>> sorted(L, key=float) # Ascending
['0.025', '0.564', '0.564', '0.656', '0.665', '0.784', '0.787', '0.789', '0.847', '0.885', '0.998', '1.001', '1.012', '1.055', '1.121', '1.197', '1.548', '1.552', '1.555', '1.785', '1.958', '1.987', '1.989', '1.998', '2.001', '2.021', '2.110', '2.112', '2.118', '2.121', '2.131', '2.546', '2.658', '2.987', '3.001', '3.154', '3.212', '3.221', '3.250', '3.325', '3.458', '3.589', '3.658', '4.000', '4.112', '4.165', '4.785', '5.234', '5.454', '13.746']
>>> sorted(L, key=float, reverse=True) # Descending
['13.746', '5.454', '5.234', '4.785', '4.165', '4.112', '4.000', '3.658', '3.589', '3.458', '3.325', '3.250', '3.221', '3.212', '3.154', '3.001', '2.987', '2.658', '2.546', '2.131', '2.121', '2.118', '2.112', '2.110', '2.021', '2.001', '1.998', '1.989', '1.987', '1.958', '1.785', '1.555', '1.552', '1.548', '1.197', '1.121', '1.055', '1.012', '1.001', '0.998', '0.885', '0.847', '0.789', '0.787', '0.784', '0.665', '0.656', '0.564', '0.564', '0.025']