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输入可能变得非常大).

解决方法:

你可能想要这样的东西:

import collections
import itertools

def build_catalog(L):
    counter = itertools.count().next
    names = collections.defaultdict(counter)
    result = []
    for t in L:
        new_t = [ names[item] for item in t ]
        result.append(new_t)
    catalog = dict((name, idx) for idx, name in names.iteritems())
    return result, catalog

使用它:

>>> input = [('dog', 'dog', 'cat', 'mouse'), ('cat', 'ruby', 'python', 'mouse')]
>>> outputlist, outputmapping = build_catalog(input)
>>> outputlist
[[0, 0, 1, 2], [1, 3, 4, 2]]
>>> outputmapping
{0: 'dog', 1: 'cat', 2: 'mouse', 3: 'ruby', 4: 'python'}
上一篇:Python – 加快列表排列的生成(以及检查Dict中是否有permations的过程)


下一篇:python – 更有效地使用itertools.groupby()