Advanced Python Idioms BCHB 524 Lecture 9 BCHB
Advanced Python Idioms BCHB 524 Lecture 9 BCHB 524 - Edwards
Outline l Sequences, iteration, and iterables l Comprehensions l Functional Programming l Exercises BCHB 524 - Edwards 2
Sequences and Iterables l Anything that supports: l Iterables we know about: l l l Strings, lists, sets, tuples Dictionaries (keys(), values(), items()) Files (line by line) Iterable → list, Iterable → set, etc. Pair iterable → dictionary! BCHB 524 - Edwards 3
Iterables # sequences are iterable -> build list a. List = list('abcdef') print "String abcdef as a list: n ", a. List # sequences are iterable -> build set (no duplicates) a. Set = set('abcdef') print "String abcdef as a set: n ", a. Set # Two iterables can be paired up using the zip function keys = [1, 2, 3, 4, 5] values = 'abcde' a. List. Of. Pairs = zip(keys, values) print "A list of pairs: n ", a. List. Of. Pairs # list of pairs are iterable -> build dict a. Dict = dict(a. List. Of. Pairs) print "A dictionary from a list of pairsn BCHB 524 - Edwards ", a. Dict 4
Special Iterable Functions l zip l l enumerate l l single value from many map, filter l l iterates over (index of item, item) sum, max, min, all, any l l merges two or more iterables Applies function or test to each element sorted, reversed l provides the items in sorted or reversed order BCHB 524 - Edwards 5
Enumerate # sequences are iterable -> build list a. List = list('abcdef') # enumerate get index with item for i, c in enumerate(a. List): print i, c # exactly equivalent to i = 0 for c in a. List: print i, c i += 1 BCHB 524 - Edwards 6
Map # Numbers in a string. . . split into a list numbers = '1, 2, 3, 4, 5, 6' number_list = numbers. split( ', ') # Print the list, and manipulate its values! print number_list[0] += 1 # Fix the problem, apply the int function to each item number_list = map(int, number_list) # Print the new list and check we can manipulate its values. . . print number_list[0] += 1 print number_list # Now to print it back out print ", ". join(number_list) # Fix the problem, apply the str function to each item number_list = map(str, number_list) # Print the new list and check that we can do a join print number_list print ", ". join(number_list) BCHB 524 - Edwards 7
Sorted, Reversed # Make a list a. List = list('abcdef') print "a. List: n ", a. List # print the list sorted and reversed. . . print "Sorted: n ", sorted(a. List) print "Reversed: n ", reversed(a. List) print "Reversed in list: n ", list(reversed(a. List)) BCHB 524 - Edwards 8
Comprehensions l Comprehensions build lists using iteration [ expr for item in iterable ] # Make the times two table. . times. Two = [ 2*x for x in range(10) ] # Make it another way times. Two. Too = [] for x in range(10): times. Two. Too. append(2*x) print "times. Two: n ", times. Two print "times. Two. Too: n ", times. Two. Too BCHB 524 - Edwards 9
Functional Programming l Python lets us treat functions as a basic immutable data-type. def f(x): return 2*x g = f print f(1), g(2), f(3), g(4) l We can’t change them after they are defined, but we can pass them in to functions. BCHB 524 - Edwards 10
sorted, revisited l l The sorted function permits a keyword parameter: key is a function which returns the sort value # Initialize a new list a. List = [1, -2, 3, -4, 5, -6] # Print the list as is and sorted print "a. List: n ", a. List print "Sorted: n ", sorted(a. List) # Define absolute value sort key def abs. Sort. Key(x): return abs(x) # Define negative value sort key def neg. Sort. Key(x): return -x # Demonstrate alternative sorting keys print "Sorted by absolute value: n " , sorted(a. List, key=abs. Sort. Key) print "Sorted by negative value: n " , sorted(a. List, key=neg. Sort. Key) BCHB 524 - Edwards 11
Lambda functions l l Sometimes, the functions are so simple, we don’t want to define them formally. l Usually used with sorted… Useful key functions: l Case insensitive: sorted(words, key=lambda s: s. lower()) l By dictionary value: sorted(dict. items(), key=lambda p: p[1]) l Also useful for map: map(lambda x: 2*x, (1, 2, 3, 4, 5, 6)) BCHB 524 - Edwards 12
Exercises Write a reverse complement function (and package it up as a program) as compactly as possible, using the techniques introduced today. 1. l Hint: Use a dictionary for complement, map to apply the get method, reversed, and join. Write a program to compute and output the frequency of each nucleotide in a DNA sequence using a dictionary (see lec. 8). 2. l Output the frequencies in most-occurrences to leastoccurrences order. BCHB 524 - Edwards 13
Homework 5 l l l Due Tuesday, October 9 th. Submit using Canvas Make sure you work through the exercises from the lecture. Exercise 1 from Lecture 8 Exercises 1 and 2 from Lecture 9 BCHB 524 - Edwards 14
- Slides: 14