Why not sorted sort the results I want?

 

data source:

a = [ '7465', ' 7514', '8053', '8267', '8507', '8782', '9091', '9292', '9917', '10000', '10009'] 

I thought b It should be small to large sort, but the results, obviously not the case

 1 In [1]: a =  ['7465', '7514', '8053', '8267', '8507', '8782', '9091', '9292', '9
 2    ...: 917', '10000', '10009']                                                 
 3 
 4 In [2]: b = sorted(a)                                                           
 5 
 6 In [3]: b                                                                       
 7 Out[3]: 
 8 ['10000',
 9  '10009',
10  '7465',
11  '7514',
12  '8053',
13  '8267',
14  '8507',
15  '8782',
16  '9091',
17  '9292',
18  '9917']

problem analysis:

Why does this happen? Carefully looked at the data in the list, is the character, I expected result is that these numbers are sorted from small to large, so is it the sort is in accordance with the ordering of characters, rather than data

 

Next to test ideas:

Converting character data one by one in the list is an int, then sort, sort really it expected as a result

1 a=['7465', '7514', '8053', '8267', '8507', '8782', '9091', '9292', '9917', '10000', '10009']
2 
3 for i in range(len(a)):
4     a[i]=int(a[i])
5 b = sorted(a)
6 print(b)

Results of the:

[7465, 7514, 8053, 8267, 8507, 8782, 9091, 9292, 9917, 10000, 10009]

 

to sum up:

When using the sort list, do pay attention to the type of sequence elements within!

Especially not to use digital as digital character!

Guess you like

Origin www.cnblogs.com/kaerxifa/p/11419899.html