python中的高效列表映射

Joe*_*oey 4 python mapping dictionary list python-itertools

我有以下输入:

input = [(dog, dog, cat, mouse), (cat, ruby, python, mouse)]
Run Code Online (Sandbox Code Playgroud)

并尝试输出以下内容:

outputlist = [[0, 0, 1, 2], [1, 3, 4, 2]]

outputmapping = {0:dog, 1:cat, 2:mouse, 3:ruby, 4:python, 5:mouse}
Run Code Online (Sandbox Code Playgroud)

关于如何处理可读性的任何提示(var输入可能变得非常大).

Tho*_*ers 6

你可能想要这样的东西:

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
Run Code Online (Sandbox Code Playgroud)

使用它:

>>> 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'}
Run Code Online (Sandbox Code Playgroud)