2

我有这个东西

mydict = OrderedDict({'a':'1', 'd':'2','f':'1', 'i':'2','m':'1', 'k':'2'})

现在假设我有这样的列表

l = [i,k]

所以我想根据列表订购 mydict l。所以这i,k将是前两个项目,然后其他项目保持原来的顺序

我想以尽可能少的编码来做到这一点。在 Python 中

4

1 回答 1

5

使用unique_everseen来自 itertools 的配方。

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

>>> from itertools import *
>>> lis = ["i","k"]
>>> mydict = OrderedDict([('a', '1'), ('d', '2'), ('f', '1'), ('i', '2'), ('k', '2'), ('m', '1')])
# A list is used in creating the OrderedDict, a dict would lose initial order
>>> OrderedDict((key,mydict[key]) for key in unique_everseen(chain(lis,mydict)))
OrderedDict([('i', '2'), ('k', '2'), ('a', '1'), ('d', '2'), ('f', '1'), ('m', '1')])
于 2013-05-15T09:25:28.980 回答