似乎构建字典/映射是关键,使用它只是主题的变体。甚至构建字典也会是一个主题的变体——更好/更差/简单/复杂是读者的心声。
>>> import itertools
>>> ordinatates = itertools.count(0)
>>> a = ['a', 'b', 'c', 'a', 'a', 'c', 'c']
>>> unique = sorted(set(a))
>>> d = {thing:ordinal for thing, ordinal in zip(unique, ordinates)}
应用它
>>> list(map(d.get, a))
[0, 1, 2, 0, 0, 2, 2]
>>>
如果a 中有不在d 中的项目,它将抛出 KeyException。
类似的,同样的警告:
>>> import operator
>>> a = ['a','b','c', 'a', 'a', 'c','c']
>>> m = map(operator.itemgetter, a)
>>> [get(d) for get in m]
[0, 1, 2, 0, 0, 2, 2]
>>>
类似
class Foo(dict):
def __call__(self, item):
'''Returns self[item] or None.'''
try:
return self[item]
except KeyError as e:
# print or log something descriptive - print(repr(e))
return None
>>> ordinates = itertools.count(0)
>>> a = ['a','b','c', 'a', 'a', 'c','c']
>>> unique = sorted(set(a))
>>> d = Foo((thing,ordinal) for thing, ordinal in zip(unique, ordinates))
>>> result = list(map(d, a))
>>> result
[0, 1, 2, 0, 0, 2, 2]
>>>
所有假设您想要排序项目的序号位置 - 因为您的示例列表很方便地进行了 预 排序。如果您要查找列表中第一次出现独特事物的位置,请按如下方式构建映射:
import itertools
ordinal = itertools.count()
b = ['c','b','c', 'a', 'a', 'c','c']
d = {}
for thing in b:
if thing in d:
continue
d[thing] = next(ordinal)
应用
>>> list(map(d.get, b))
[0, 1, 0, 2, 2, 0, 0]
>>>
@Abdou 在他的评论中提到了这一点,但你没有回答。
如果你有一个单行恋物癖可以写成
d = {}
d.update((thing,d[thing] if thing in d else next(ordinal)) for thing in b)