python - Understanding list comprehension vs traditional loop and build -


i'm trying nail understanding , best use of lists, have come across list comprehension , read plenty them, choking on 1 particular burning question.

given challenge:

def matrix_mult(m1, m2):     """       >>> matrix_mult([[1, 2], [3,  4]], [[5, 6], [7, 8]])       [[19, 22], [43, 50]]       >>> matrix_mult([[1, 2, 3], [4,  5, 6]], [[7, 8], [9, 1], [2, 3]])       [[31, 19], [85, 55]]       >>> matrix_mult([[7, 8], [9, 1], [2, 3]], [[1, 2, 3], [4, 5, 6]])       [[39, 54, 69], [13, 23, 33], [14, 19, 24]]     """ 

i created solution, me seemed logical , matched previous programming experience, more or less typed thinking ...

# 1 using traditional list buildup method     res = [] in range(len(m1)):     sub = []     j in range(len(m2[0])):         sub.append(row_times_column( m1, i, m2, j ))     res.append(sub) return res 

then found solution featured 'list comprehension' (i renamed vars match mine in order better grok diffs between 2 solutions:

# 2 using list comprehension res = [[0] * len(m1) x in xrange(len(m2[0]))] in range(len(res)):    j in range(len(res[i])):        res[i][j] = row_times_column(m1, i, m2, j) return res 

the second solution building 0 based matrix matches shape of intended answer, but method meant "list comprehension", or there more going on here?

here row_times_column() def, fullness.

def row_times_column(m1, row, m2, column):     """       >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 0)       19       >>> row_times_column([[1, 2], [3, 4]], 0, [[5, 6], [7, 8]], 1)       22     """     = 0     index, value in enumerate(m1[row]):        += value * m2[index][column]     return 

i suspect there third (and many more) way of solving this, using lambda, thought i'd ask comment on these 2 first.

example taken http://openbookproject.net/thinkcs/python/english2e/ch09.html

edit got better handle on list comprehension now, thx answers here given.

still, can explain logic of creating blank matrix correct answers placed vs creating new list?

list comprehension way of creating list based on list. (or other iterable item)

for instance, if have list a = [1, 2, 5, 7], create list, b, containing values of a doubled in 2 ways.

without list comprehensions

b = [] e in a:     b.append(2*e) 

with list comprehensions

b = [2*e e in a] 

there's nothing more that. it's nice syntax building lists based on lists.

see also:


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -