python 3.x - Why doesn't variable increment in list comprehension -
given;
a = [[1,2,3,4], [5,6,7,8], [9,0,1,2], [3,4,5,6]]
i want list of diagonal - using single list comprehension statement.
[1,6,1,6]
i expected with
i = -1 # (cheating didn not know how else it) dia_1 = [r[i] (r,i) in [(r, i+1) r in a]]
but result;
[1, 5, 9, 3]
so, must not incrementing:
q1: why doesn't 'i' increment?
q2: how fix statement achieve desirede result?
why not like
dia_1 = [a[n][n] n in range(len(a))]
or
dia_1 = [r[n] n, r in enumerate(a)]
while second approach more aesthetically pleasing me personally, yield identical results. both assume n
th row has n
th element, regardless of actual shape of list.
to answer question incrementing, there no assignment i
anywhere in comprehension. i + 1
has constant value 0
, fetching first column, expected.
Comments
Post a Comment