One 、
Two 、
python Input string to list in
summary
This article mainly talks about sort And sorted The main difference , In order to use it correctly
One 、sort() Can only be used for list ;sorted() Can be used for all iteratible objects ;
such as :
str_a = "blue"print(sorted(str_a))>>>['b', 'e', 'l', 'u']
Two 、sort() To sort a list is to sort in place , Does not return a new list ;
sorted() A new list will be returned after sorting ;
such as :
about sort() Come on :lis_a = [5,4,3,2,1]lis_a.sort()print(lis_a)>>>[1, 2, 3, 4, 5] about sorted() Come on :lis_a = [5,4,3,2,1]lis_b = sorted(lis_a)print(lis_a)print(lis_b)>>>[5, 4, 3, 2, 1]>>>[1, 2, 3, 4, 5]
Why there are two ways , Instead of simply using one method ?
Here's my personal understanding , Maybe not all right , Please correct any mistakes . In my submission , Because the list is a variable sequence , So it can be modified in situ , That is, you can sort in place . But for iteratable objects such as strings , Is immutable , It cannot be modified in its original place .sort() Method belongs to in situ modification , So it may only be used for lists , For other immutable iteratible objects, another kind of sorted() Method .
There is also a little shallow ,sort() Because it is sorted in place , Therefore, the original list has been modified . If you don't want to change the original list , that python Provides sorted() Method .
Some people may not understand what it means to modify in place ? If you understand, you don't have to look down .
such as :
Variable sequence :lis_a = ['a','b','c','d','e','f'] Immutable sequence :str_a = "abcdef"lis_a[0] = 1str_a[0] = 1 # The sequence can be indexed print(lis_a)print(str_a)
So it's a mistake
But for a list it is :
python Input string to list inpython Use in input() To enter a string from the keyboard And this operation is a little careless == There will be some problems ,== For example, convert the input string into a list :
a = input()lis = list(a)print(lis)
When you enter a line of strings separated by spaces :
Then you may want me to a If you remove the space in the ok 了 , You might think of using replace Method .== But what if you enter a negative number ?==
So face these problems , We can use split() Method :
a = input().split()lis = list(a)print(lis)
When separated by spaces split() There is no need to put any parameter in brackets :
If you separate them with commas , Then it needs to be changed to :input().split(",")
Actually , Generally, when using space spacing , It is easy to have the above problems .
summaryThis is about python in sort() and sorted() That's all for the differences and usages , More about python sort() and sorted() Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !