i have 4 arrays, say, a, b, c , d, of same size numelements, , want remove 0s in them. if has zero, b, c , d have 1 too, in same position. thinking loop on elements of a:
for n in range(numelements): if a[n]==0: a.pop(n) b.pop(n) c.pop(n) d.pop(n) of course, doesn't work, because popping 0s arrays reduces sizes, end trying access a[numelements-1], when numelements-m long. know should work array copies, arrays quite long , i'd keep memory consumption low, since i'm working in java virtual machine (don't ask :(((( ). also, i'd approach efficient, of readable (this code must maintained python illiterates me, need kiss). thanks,
deltaquattro
if have zeros in same place, loop on index in reverse , remove index each list:
for in reversed(range(numelements)): if not a[i]: del a[i], b[i], c[i], d[i] by looping on list in reverse, keep indices stable (only elements past current index have been removed, shrinking tail of lists). since not using return value of list.pop() (all 0s anyway, right?), may use del on list index instead.
i used reversed(range(numelements)) here instead of calculating more strenuous range(numelements - 1, -1, -1); efficient lot more readable. reversed() function returns iterator, handling reversed number sequence efficiently. on python 2, can same xrange():
for in reversed(xrange(numelements)): demo:
>>> = [1, 2, 0, 4, 5, 0] >>> b = [2, 4, 0, 10, 9, 0] >>> c = [5, 3, 0, 10, 8, 0] >>> d = [10, 3, 0, 1, 34, 0] >>> in reversed(range(numelements)): ... if not a[i]: ... del a[i], b[i], c[i], d[i] ... >>> a, b, c, d ([1, 2, 4, 5], [2, 4, 10, 9], [5, 3, 10, 8], [10, 3, 1, 34])
Comments
Post a Comment