This week I had a good time with python. Yes, I have learnt few things which I feel worth to share here.
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. One can find out the number of occurrence of the list items.
>>>from collections import Counter
# list1 is a list/array which contains numbers
>>>list1 = [1,2,4,5,7,3,5,0,8,5,4,5,4,5,6,7,3,1,2,0,8,3,4,5,2,1,2,3,1,2]
# Counter will convert list1 into dictionary
>>>count = Counter(list1)
>>># most_common function will give the series of all the elements and its corresponding occurrences.
[(5, 6), (2, 5), (1, 4), (3, 4), (4, 4), (0, 2), (7, 2), (8, 2), (6, 1)]
>>># get the most common element by sending 1 to the function
>>>count.most_common(1) # get element & no. of occurrence as dict
>>>most_common = count.most_common(1) # Get the most common element
In the past I have used strip to strip out some letters from a string. Example
But I strip() is also used to remove all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
I was looking for a module in python which used to rename all the specific type (eg. .docs, .txt, .py) files in a particular directory.
# Go to a directory get all the files of specific type ( lets say “.xls”)
# and rename it with ‘os.rename’
>>> import glob # used to get all the dir / file from a specified path
>>>path = “C:\\Users\\Vaidegi\\Desktop\\*.xls“
>>>file_names_with_path = glob.glob(path+“*.xlsx“) # to get all the excel files name
>>>for i in range(len(file_names_with_path )):
. . . os.rename(file_names_with_path[i], ‘student‘+i+‘.xls‘)