#comprehensions.py #demo some list comprehensions # [ expression context] # expression: what to do with each element of the list # context: which list elements to select. An arbirtray number of for and if statements. import math import random # [expr for val in collection ] #list of first 100 perfect squares perf_sqrs = [i**2 for i in range(101)] print(perf_sqrs) # [expr for val in collection if condition ] #list of those perfect squares that are divisible by 5 print( [i for i in perf_sqrs if i%5==0]) #or combine the two above: [i**2 for i in range(101) if i**2%5==0] v = [1,2,3,4] #scalar multiplication: 4v print([4*i for i in v]) #Note: 4*v does something different: print(4*v) #repeated concatenation: 4*v = v+v+v+v # expr needn't use for loop's variable num_pts = 10 points = [(random.randint(-10,10),random.randint(-10,10)) for i in range(num_pts)] print(points) # more than one collection: [expr for val1 in collection1 for val2 in collection2] #Cartesian product All pairs u = [10,20,30] prod = [(i,j) for i in u for j in v] #list of tuples print(prod) letters = 'abcd' print([let*n for n in range(1,5) for let in letters]) print([let*n for let in letters for n in range(1,5)]) letters = 'qwerty' lst = sorted([let*n for n in range(1,5) for let in letters]) print(lst) #Cartesian product All triples... etc w = {'cat','dog','horse','rat'} #set prod_triples = [[i,j,k] for i in u for j in v for k in w \ if len(k)<4 and j!=1] #list of lists print(prod_triples) keys = ("name","age","city") # like a record/struct values = [("bob",23,"boston"),("alice",24,"naha"),("carol",51,"kadena")] dict_list = [dict([(keys[i],values[d][i]) for i in range(len(keys))]) for d in range(len(values))] def area(r): return math.pi*r**2 radii = [1,2,3,4,5,6,10] areas = [area(r) for r in radii] print(areas) freqs = [0,0,12,34,0,123] # list of tuples: (index,value) from non-zero entries of list print([(index,freqs[index]) for index in range(len(freqs)) if freqs[index]>0]) tup_list = [('asdf',10), ('qwer',20), ('yuio',30), ('cv',40)] # list of tuples first = [x for x,y in tup_list] #extract first of each tuple bigs = [y for x,y in tup_list if y>=30] ###################### VECTORS ######################## # dot product of same-sized vectors u and v # sum( [u[i]*v[i] for i in range(len(u))] ) #MAGNITUDE (length, norm) of a vector u # math.sqrt(sum( [a**2 for a in u] )) ###################### MATRIX ##################### #create a 2D list, i.e. matrix, initialized to 0 rows = 5 cols = 4 M = [[0 for j in range(cols)] for i in range(rows)] # or M = [[0]*cols for i in range(rows)] # or #M = [[0]*cols] * rows # NO! this is a list of the SAME list #col_th column of a matrix col = 3 [row[col] for row in M] #SUM matrix of two same-sized matrices A and B #[[A[i][j]+B[i][j] for j in range(len(A[0]))] for i in range(len(A))] #a list of 200 string-numbers, into a 10x20 matrix import random M_list = [str(random.randint(1,100)) for num in range(200)] rows = 10 cols = 20 M = [[int(M_list[row*cols+col]) for col in range(cols)] for row in range(rows)] #eliminate every other column M = [[random.randint(1,12) for i in range(6)]for rows in range(5)] Me = [[row[::2] for row in M]] #file format: #fips,name,state,population,percapIncome,medianHouseholdIncome,area #5137,Stone,AR,12663,17190,31364,606.41 counties = [line.rstrip().split(',')[1:4] for line in open("datafile_countiesCSV.txt")\ if not line.startswith("fips")] #skip header first line print(counties) print() counties = [[name,state,int(population)] for (name,state,population) in counties\ if int(population)<50000] print(counties) #can this be all in one comprehension? #file format: lines of numbers: #467 479 487 491 499 503 509 521 523 primes = [line.split() for line in open("primes64K.txt")] primes = [int(num_s) for line in primes for num_s in line] print(len(primes),primes[0],primes[len(primes)-1]) ################ Dictionary comprehension ################ names = ['bob','alice','carol','ted','zippy'] nums = [23,45,32,41,5] my_dict = {name:num for name,num in zip(names,nums)} print(my_dict) ################# Set comprehension ####################### nums = [2,4,3,2,5,1,2,4,5,6,7,6,3] my_set = {n for n in nums} # or: my_set = set(nums) print(my_set) nums = list(my_set) # eliminate dups print(nums) {(x,y)for x in range(3) for y in range(4)} alice = ''' Alice was beginning to get very tired of sitting by her sister on the bank and of having nothing to do once or twice she had peeped into the book her sister was reading but it had no pictures or conversations in it and what is the use of a book thought Alice without pictures or conversation''' longwords = [w for w in alice.split() if len(w)>=6] [(lambda s: (True,s) if 'c' in s else(False,s))(s) for s in words]