Code
import pandas as pd
=pd.read_csv("https://raw.githubusercontent.com/TheEconomist/big-mac-data/master/output-data/big-mac-raw-index.csv") df
Jakob Johannesson
August 2, 2024
old_list = [2,4,2,4,5,3,6]
new_list = [i*2 for i in old_list]
new_list
Adding the if-statement in the end of the comprehension
[i*2 for i in old_list if i%2==True]
The if-statement acts as a filter.
[10, 9]
1st if statements adds logic, 2nd if statement filters the results.
Shorter and better than the for loop. Enumerate takes a string, finds the index and the value of it and adds it to a tuple. we can filter it to grab even indexed values in the string. Code below.
Let’s say we want to uppercase the ‘aeuio’ chars. This is a 3-step process, first we add the for-loop for idx,char in enumerate(old_list), then we add the filter if idx % 2 == 0, finally we add char.upper() if char in ‘aeuio’ else char. Full code below.
You may have multiple nested for loops, you can manage that with comprehensions too using code like this.
[(1, 0),
(2, 0),
(2, 1),
(3, 0),
(3, 1),
(3, 2),
(4, 0),
(4, 1),
(4, 2),
(4, 3)]
Add a filter in between loop 1 and loop 2 in order to filter in loop 1. If you want to filter loop 2, you add the filter after loop 2.
Example with dict.
{0: 'a', 1: 'b', 2: 'c', 3: 'e', 4: 'a', 5: 'b', 6: 'c', 7: 'e'}
Careful with removing duplicate values. Switching index with key will drop duplicates.
Code of a switched index and key.
it will take the one in the end of the list.
Here we will get a index for each pair of key and value, which is smooth way of unpacking the data that is inside.
You may add more arrays if needed.