> I have two arrays that are of the same dimension but having 3 different > values: 255, 1 or 2. > I would like to set all the positions in both arrays having 255 to be > equal, i.e., where one array has 255, I set the same elements in the > other array to 255 and visa versa. Does anyone know how to do this > without using for loops?
>>> # make some sample data >>> c = 20 >>> import random, itertools >>> a1 = [(1,2,255)[random.randint(0,2)] for x in xrange(c)] >>> a2 = [(1,2,255)[random.randint(0,2)] for x in xrange(c)] >>> >>> # actually do the work >>> all = [(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)] >>> b1 = [x[0] for x in all] >>> b2 = [x[1] for x in all] >>> a1, a2 = b1, b2 # if you want them to replace the originals Seems to do what I understand that you're describing using "no" loops (other than those implied by list comprehension). There may be some nice pythonic way to "unzip" a list of tuples created by zip() but I couldn't scare up such a method, and searching for "unzip" turned up a blizzard of hits for dealing with ZIP files, not for unzipping that which was previously zip()'ed. My google-foo must be broken. :) Otherwise, you could just do >>> b1,b2 = magic_unzip([(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)]) or >>> a1,a2 = magic_unzip([(x==255 or y==255) and (255, 255) or (x,y) for (x,y) in itertools.izip(a1,a2)]) if you just want to dispose of your originals. -tkc -- http://mail.python.org/mailman/listinfo/python-list