python 中的高效列表映射
我有以下输入:
input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
并尝试获得以下输出:
outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]
outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
有关如何处理给出的可扩展性的任何提示(var 输入可能会变得非常大)。
I have the following input:
input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
and trying to have the following output:
outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]
outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
Any tips on how to handle given with scalability in mind (var input can get really large).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想要类似的东西:
使用它:
You probably want something like:
Using it:
此类将自动将对象映射到递增的整数值:
示例用法,用于您的输入:
This class will automatically map objects to increasing integer values:
Example usage, for your input:
这是一种可能的解决方案,尽管它不是最好的。如果您通过预先分配列表中的每个条目事先知道有多少个元素,则可以稍微提高效率。
Here is one possible solution, although it isn't the greatest. It could be made slightly more efficient if you know how many elements each entry in the list will have before-hand, by pre-allocating them.
我在我的项目中经常遇到同样的问题,所以我不久前完成了一个类,它正是这样做的:
用法示例:
I had the same problem quite often in my projects, so I wrapped up a class some time ago that does exactly this:
Usage example: