# datastructures.py ''' More on lists and tuples and dictionaries. ''' # # List Comprehensions. # squares = [x**2 for x in range(10)] [(x, y) for x in [1, 2, 3] for y in [3, 1, 4]] # Some control. [x for x in range(10) if x > 5] # Nested list comprehension. matrix = [[x+10*y for x in range(3)] for y in range(3)] # Transpose. zip(*matrix) # Delete and object. del(matrix) # # Tuples # (x, y) = (4, 3) tt = (x, y) len(tt) # Create a tuple with 0 and 1 item. singleton = (2, ) # Transform an iterable into a tuple. (x, y) = tuple([1, 2]) # # Dictionaries (associative arrays) # tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 tel.keys() tel.items() tel.values() del(tel['sape']) 'guido' in tel 'jack' not in tel dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) # Looping with dictionaries. knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v) # # Comparing data structures. # (1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] 'ABC' < 'C' < 'Pascal' < 'Python' (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1)