To illustrate, the sum built-in sums items in a sequence:summing all items in our matrix's rows on request:
M = [[1, 2, 3], # A 3 ? 3 matrix, as nested lists [4, 5, 6], # Code can span lines if bracketed [7, 8, 9]] # from w w w. j a v a 2s . c om G = (sum(row) for row in M) # Create a generator of row sums print( next(G) ) # iter(G) not required here print( next(G) ) # Run the iteration protocol next() print( next(G) )
The map built-in can generate the results of running items through a function, one at a time and on request.
M = [[1, 2, 3], # A 3 ? 3 matrix, as nested lists [4, 5, 6], # Code can span lines if bracketed [7, 8, 9]] # from w ww . ja v a 2 s. c om print( list(map(sum, M)) ) # Map sum over items in M
Comprehension syntax can also be used to create sets and dictionaries:
M = [[1, 2, 3], # A 3 ? 3 matrix, as nested lists [4, 5, 6], # Code can span lines if bracketed [7, 8, 9]] # w w w. j av a 2s .com print( {sum(row) for row in M} ) # Create a set of row sums print( {i : sum(M[i]) for i in range(3)} ) # Creates key/value table of row sums
Lists, sets, dictionaries, and generators can all be built with comprehensions:
print( [ord(x) for x in 'test'] ) # List of character ordinals print( {ord(x) for x in 'test'} ) # Sets remove duplicates print( {x: ord(x) for x in 'test'} ) # Dictionary keys are unique print( (ord(x) for x in 'test') ) # Generator of values # ww w .ja v a2 s . c o m