This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together . This article mainly talks about sort And sorted The main difference , In order to use it correctly
such as :
str_a = "blue"
print(sorted(str_a))
>>>['b', 'e', 'l', 'u']
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]
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 .
such as :
Variable sequence :lis_a = ['a','b','c','d','e','f']
Immutable sequence :str_a = "abcdef"
lis_a[0] = 1
str_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 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 .
Title Map : One man fixes the
Environmental Science : python