In week 5 lab, we learned something new called list comprehensions, which can reduce your code whenever you have to loop over your list. Normally we use a for loop and an if statement within that for loop to modify the list. By using list comprehensions, we can easily use one simple line to do the job. For example, if we want to generate a new list of odd integers from 1 to 10, using for loops. First we need to create an empty list, then for each number in range from 1 to 10, we append only the odd number among all to the new list. By using list comprehensions, we can just write new_list = [ n for n in range(10) if n % 2]. Nevertheless, when the circumstance becomes too complicated, we prefer to use the for loops.
Zip is a bulit-in class in python, which helps a lot when we use list comprehensions. By defining a new class of zip on two lists, it will return a list of tuples that containing each item in both lists. Of course one that uses zip() has to note that lists with different length have to be treated differently.
Filter is a bulit-in function in python that can be use in list comprehensions as well. When we generating a new list from the old one, we often set certain conditions on the item we want. The if statement usually does the job in a for loop. Here by using filter(function, iterable), it is equivalent to the generator expression [item for item in iterable if function(item)].
No comments:
Post a Comment