python - Re assign a list efficiently -
this mwe of re-arrainging need do:
a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] b = [[], [], []] item in a: b[0].append(item[0]) b[1].append(item[1]) b[2].append(item[2]) which makes b lool this:
b = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] i.e., every first item in every list inside a stored in first list in b , same lists 2 , 3 in b.
i need apply big a list, there more efficient way this?
there much better way transpose rows , columns:
b = zip(*a) demo:
>>> = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] >>> zip(*a) [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] zip() takes multiple sequences arguments , pairs elements each form new lists. passing in a * splat argument, ask python expand a separate arguments zip().
note output gives list of tuples; map elements lists needed:
b = map(list, zip(*a))
Comments
Post a Comment