好像構建字典/映射是關鍵,使用它將是一個主題的變化。即使構建字典也會是一個主題的變體 - 在讀者眼中是否更好/更差/簡單/複雜。
>>> 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]
>>>
它會拋出的KeyException如果在a
不在d
項目。
相似,同樣的警告:
>>> 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]
>>>
所有這一切假設你想要的分類項的序號位置 - 爲你的榜樣名單是方便pre -sorted。如果您正在尋找在一個獨特的東西第一次發生在列表中的位置,構建這樣的映射:
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)
套件未訂購。 –
而不是'list(set(A))'(它以任意順序創建一個列表),使用'sorted(set(A))'。 – DeepSpace
您示例中的「A」中的項目是否只是大寫字母?到目前爲止的答案取決於這是數據的準確表示。 – roganjosh