Consider the employees and try to find all the employees having salary greater than or equal to 1 lakh as top earners
To find the top earners the code is
employees = {
'Alice': 100000,
'Bob': 98000,
'Cena': 127000,
'Dwayne': 158000,
'Frank': 88000
}
# find the top earner (every one with salary greater than or equal to 1 lakh)
top_earners = []
for name,salary in employees.items():
if salary >= 100000:
top_earners.append((name,salary))
print(top_earners)
One liner
## One-liner
top_earners = [(n,s) for n,s in employees.items() if s >= 100000 ]
print(top_earners)
Reading a File
Traditional approach:
file_name = 'data/info.txt'
file_object = open(file_name)
lines = []
for line in file_object:
lines.append(line.strip())
print(lines)
file_object.close()
one_liner
print([line.strip() for line in open('data/info.txt')])
Combinining List Comprehensions and Slicing
Assume we have a large dataset which has stock market prices of some stock during a week
To create a data sample for some alogrithm, we decided to take every alternate stock price in a day