Issue
I wrote a very basic python code, but it didn't work:
str = "asddasdvsatvsyvcstvcsacvsacvsaifteiopvnvbcshavsdsdzasbbnyju"
dict = {}
for i in str:
dict[i] = dict.get(i,0)+1
print(list(dict.items()).sort())
then I just changed the sequence of functions and separated them, and surprisingly it worked!
str = "asddasdvsatvsyvcstvcsacvsacvsaifteiopvnvbcshavsdsdzasbbnyju"
dict = {}
for i in str:
dict[i] = dict.get(i,0)+1
mylist = list(dict.items())
mylist.sort()
print(mylist)
What's happened from my first to second code that makes it work?
Solution
.sort()
sorts the list in-place (it changes the list itself and doesn't make a copy). But it doesn't return anything (other than None).
If you do
print(list(dict.items()).sort())
You print the return value of sort()
-- which is None.
But with
mylist.sort()
print(mylist)
You first sort, and then you print the value of mylist
. That's what you want.
You could also have done
print(sorted(mylist))
But that leaves mylist
unchanged.
Answered By - RemcoGerlich
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.