list的字符串转化成浮点型或整形的方法
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def insertion_sort(sort_list):
iter_len = len(sort_list)
if iter_len < 2:
return sort_list
for i in range (1, iter_len):
key = sort_list[i]
j = i - 1
while j >= 0 and sort_list[j] > key:
sort_list[j+1] = sort_list[j]
j = j - 1
sort_list[j+1] = key
return sort_list
if __name__ == "__main__":
num = raw_input("enter the numbers : ").split(' ')
print num
print "the sorted nums are :"
print insertion_sort(num)
>>>
enter the numbers : 12 35 87 8 3 2
['12', '35', '87', '8', '3', '2']
the sorted nums are :
['12', '2', '3', '35', '8', '87']
上面的这个只能按ascii码排列,因为处理对象是字符串,想请教下如何才能把它当做数字来排序呢?
另外方法应该有很多种,内置函数sort,或通过类型转换后再排序等,方法不限,都可以作为答案,希望大家都贴上来,我研究研究!
谢谢!
[解决办法]
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.>>> x = ['12', '35', '87', '8', '3', '2']>>> x['12', '35', '87', '8', '3', '2']>>> x.sort(key=lambda x:int(x))>>> x['2', '3', '8', '12', '35', '87']>>>