wh what is a list comprehension
play

Wh What is a list comprehension? Concise way to create a list from - PowerPoint PPT Presentation

2/11/20 Wh What is a list comprehension? Concise way to create a list from another list Syntax: L2 = [expression(i) for i in L1 if condition(i)] cubes = [] cubes = [i**3 for i in range(10)] for i in range(10): cubes.append(i**3)


  1. 2/11/20 Wh What is a list comprehension? • Concise way to create a list from another list • Syntax: • L2 = [expression(i) for i in L1 if condition(i)] cubes = [] cubes = [i**3 for i in range(10)] for i in range(10): cubes.append(i**3) CS 224 Introduction to Python Spring 2020 Class #08: List Comprehension Equivalent 1

  2. 2/11/20 Ex Example using files Yo Your turn: Use a list comprehension to create a list of Fahrenheit temperatures The existing list in a comprehension can be ad hoc: from a list of Centigrade temperatures. path = my_dir dF = [1.8 * c + 32 for c in dC] files = [path + ‘/’ + i for i in os.listdir(path)] for f in files: What does this comprehension do: fn = open(f, ‘r’) returns a (Python) list of files do something with fn dF = [1.8 * c + 32 for c in [randint(0, 100) fn.close() for i in range(10)]] What does this code do? elements in that list are used to create a new list in which each element also includes the path 2

  3. 2/11/20 Fi Filtering Yo Your turn again: We can choose which elements in the existing list are used to create the new list: Use a list comprehension to create a list of the odd values in a list of data. roots = [math.sqrt(i) for i in nums if i > 0] odds = [i for i in data if i % 2 == 1] avoids math domain error (sqrt of negative number) Note: len(roots) <= len(nums) 3

  4. 2/11/20 Us Using a function Mu Multiple Lists Let coords be a list containing 2-element lists of GPS coordinates: You can use multiple existing lists to create the new list: [[(lat1, lon1), (lat2, lon2)], [(lat3, lon3), (lat4, lon4)] …] pairs = [(x, y) for x in xcoords for y in ycoords] Create a list of distances between the pair of cities in each sublist. What are the elements of pairs ? - each is an (x, y) pair in the cross-product of xcoords and ycoords Function definition def distance(city1, city2): - this works even if the two input lists have different lengths # compute and return distance What if you want elements paired by position? dists = [distance(x, y) for x, y in coords] pairs = [(xcoords[i], ycoords[i] for i in range(len(xcoords))] Can use min if the input lists have different lengths. 4

  5. 2/11/20 On One more turn for you… Staying with the setup from the previous slide, create a list of the pairs of cities that are closer than threshold d: close = [[x, y] for x, y in coords if distance(x, y) < d] function in the filter 5

Recommend


More recommend