Python Learning
This week I had a good time with python. Yes, I have learnt few things which I feel worth to share here.
Counter:
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.
Example:#
>>>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.
>>>count.most_common()
[(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)
[(5, 6)]
>>>count.most_common(1)[0] # get element & no. of occurrence as dict
(5, 6)
>>>most_common = count.most_common(1)[0][0] # Get the most common element
5
Strip() :
In the past I have used strip to strip out some letters from a string. Example
>>>“AuraAuro“.strip(“A“)
“uraAuro“
But I strip() is also used to remove all whitespace at the start and end, including spaces, tabs, newlines and carriage returns.
Rename:
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
>>>import os
>>>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‘)
Author
prathap7618@gmail.com
Related Posts
How to Install WSL and Ubuntu (LTS) on the Windows platform
~Sandhiya.B and Ajay This post consolidates the information needed to set up the Ubuntu terminal on a Win 11 Machine. The Ubuntu terminal...
Read out allAmbient light sensor using a photoresistor and Arduino Uno
This project is about using a photoresistor along with an Arduino Uno board to determine the brightness of a room which is...
Read out allSmart dustbin using Arduino
The smart dustbin is built on a microcontroller-based platform Arduino Uno board which is interfaced with the Servo motor and ultrasonic sensor....
Read out allLOGIC GATES USING ARDUINO UNO
A basic gate is defined as a component with one or more inputs and one output. The inputs and outputs are all...
Read out allLAST SCHOOL STUDENTS VISIT STEMLAND
On the 14th of July students from the Last school, Auroville visited STEMLAND. The forty students accompanied by the teachers enjoyed their...
Read out allVim Editor Session
Vim Editor Session ~SriBhavani and Bakyalakshmi On 18th Jan 2022, we had a session on vim by HarshaVaradhan from AuraSemiconductors. In this...
Read out all