python - 如何从地图中一次检索 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
有没有人有更好的主意?
解决方案
经典的 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
)。
推荐阅读
- html - java angularjs spring文件上传
- regex - s/// 返回不合适的换行符
- python-3.x - 在 Python 3.x 中使用重复密钥进行 XOR 加密时出现问题
- java - 如何在拥有 html、css 和 js 文件的同时构建 Angular6 项目
- php - 如何使用 PHP 语言显示 HTML 中列的最高值
- java - 在 Java 中使用 Scanner 获取可变数量的输入
- dart - 颤振底片圆角半径
- android - 如何使 FragmentActivity 扩展 AppCompat 以使用工具栏?
- android - 程序类型已经存在 - Tipsi-Stripe
- javascript - 使用 JavaScript 将定时事件绑定到 DOM 对象