Examples from Learning Python 4th edition

M = [[1,2,3],[2,3,4],[3,4,5]
col2 = [row[1] for row in M]

[row[1] + 1 for row in M]
[row[1] for row in M if row[1] % 2 == 0]

diag = [M[i][i] for i in [0,1,2]]

G = (sum(row) for row in M)	        #Create a generator of row sums
next(G)			                #Run the iteration protocol

list(map(sum, M))		            # Map sum over items in M

#3.0 or later:
{sum(row) for row in M}	            #Create a set of row sums
{i: sum(M[i]) for i in range(3)}	   #Create key/value table of row sums

#In fact, lists, sets, and dictionaries can all be built with comprehensions in 3.0:
[ord(x) for x in 'spaam']	        #List of character ordinals
{ord(x) for x in 'spaam'}	        #sets remove duplicates
{x: ord(x) for x in 'spaam'}	      #dictionary keys are unique
posted on 2011-10-26 13:05  Aeol Kong  阅读(266)  评论(0)    收藏  举报