Python:从右向左压缩的最快方法是什么,对此没有内置功能吗? [英] Python: What's the fastest way to zip right to left, and is there no builtin for this?

查看:61
本文介绍了Python:从右向左压缩的最快方法是什么,对此没有内置功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出2个不同长度的序列:

Given 2 sequences of different lengths:

In [931]: a = [1,2,3]
In [932]: b = [4,5,6,7]

这就是我想要的

In [933]: c = zip(reversed(a),reversed(b))
In [934]: [x for x in reversed(c)]
Out[934]: [(1, 5), (2, 6), (3, 7)]

但是我不喜欢在所有输入参数上使用反向的想法,而且我也不想重新实现自己的zip函数.

But I don't like the idea of using reversed on all my input parameters, and I also don't want to re-implement my own zip function.

所以:

  1. 是否有更快/更有效的方式来做到这一点?
  2. 有没有更简单的方法来做到这一点?

推荐答案

以下内容比其他已发布的解决方案更快,更清晰:

The following is faster and clearer than the other posted solutions:

s = zip(reversed(a), reversed(b))
s.reverse()                       # in-place

内置的 reversed 创建了一个迭代器,这些迭代器以与向前迭代相同的速度向后循环.不会产生额外的内存(输入的完整副本),并且在Python eval循环(在使用索引的其他解决方案中也是如此)的周围不会出现缓慢的行程.

The reversed built-in creates an iterator those loops backwards at the same speed as forward iteration. No additional memory (full copies of the input) are produced and there are no slow trips around the Python eval-loop (present in the other solutions that use indicies).

这篇关于Python:从右向左压缩的最快方法是什么,对此没有内置功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆