首页 > 解决方案 > 如何从地图中一次检索 2 个值 - 在 Python 3.x 中

问题描述

这是一个 Python 2.x 函数,用于处理具有 x、y 坐标的序列;请注意,参数 ints 是 map 类型:

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

我正在将其转换为 Python 3.x,并且地图对象不再是可下标的。这就是我同时解决它的方法:

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

有没有人有更好的主意?

标签: pythonpython-3.xcoordinatessubscriptalternating

解决方案


经典的 Python 习语是zip(*[iter(...)]*2),它适用于任何可迭代对象:

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

由于您正在传递map,它已经是一个迭代器,您可以省略iter

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

或者,更简单,

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

但我会保留它以保持函数更通用(有一天你可能想要传递 alist而不是 a map)。


推荐阅读