How to retrieve 2 values at a time from a map - in Python 3.x

60 views Asked by At

This is a Python 2.x function for handling sequences with x, y coordinates; please note that argument ints is of type map:

def IntsToPoints(ints):
    result = []
    for i in range(0, len(ints), 2):
        result.append(Point(ints[i], ints[i+1]))
    return result

I'm converting it to Python 3.x and the map object is no longer subscriptable. This is how I have solved it for the meantime:

def IntsToPoints(ints):
    result = []
    for i, myint in zip(range(len(list(ints))), ints):
        if i%2 == 0: x = myint
        else: result.append(Point(x, myint))
    return result

Is there anyone who has a better idea?

1

There are 1 answers

2
georg On BEST ANSWER

The classic python idiom is zip(*[iter(...)]*2), which works with any iterable:

points = [Point(x, y) for x, y in zip(*[iter(ints)] * 2)]

Since you're passing map, which is already an iterator, you can omit iter:

points = [Point(x, y) for x, y in zip(*[ints] * 2)]

or, simpler,

points = [Point(x, y) for x, y in zip(ints, ints)]

but I'd leave it in to keep the function more generic (some day you might want to pass a list instead of a map).