有没有在Python中标记列表的快捷方法?

Dir*_*Fox 2 python dictionary list

我有一个200k元素的列表.这些元素是7种不同的标签(实际上是水果列表).我需要为每个水果分配一个数字.

有快速的方法吗?

到目前为止,我已经写过了这篇文章......这需要很长时间.

dic,i = {},0.0
for idx,el in enumerate(listFruit):
    if dic.has_key(el) is not True:
        dic[el] = i
        i+=1.0
    listFruit[idx] = dic[el]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

使用带有collections.defaultdict()对象itertools.count()对象作为工厂生成下一个值; 这将避免必须自己测试每个键以及必须手动增加.

然后使用列表推导将这些数字放入列表中:

from collections import defaultdict
from functools import partial
from itertools import count

unique_count = defaultdict(partial(next, count(1)))
listFruit[:] = [unique_count[el] for el in listFruit]
Run Code Online (Sandbox Code Playgroud)

functools.partial()可调用的周围产生的包装next()功能,以确保代码工作在任一的Python 2或Python 3.

我在这里使用整数计数,从1.如果您坚持使用浮点值count(1),count(1.0)则可以替换为; 你会得到1.0,2.0,3.0,等来代替.

演示:

>>> from collections import defaultdict
>>> from functools import partial
>>> from itertools import count
>>> from random import choice
>>> fruits = ['apple', 'banana', 'pear', 'cherry', 'melon', 'kiwi', 'pineapple']
>>> listFruit = [choice(fruits) for _ in xrange(100)]
>>> unique_count = defaultdict(partial(next, count(1)))
>>> [unique_count[el] for el in listFruit]
[1, 2, 3, 2, 4, 5, 6, 7, 1, 2, 4, 6, 3, 7, 3, 4, 5, 2, 5, 7, 3, 5, 1, 3, 3, 5, 2, 2, 6, 4, 6, 2, 1, 1, 3, 6, 6, 4, 7, 2, 6, 4, 5, 2, 1, 7, 7, 7, 4, 3, 7, 3, 1, 1, 5, 3, 3, 6, 5, 6, 1, 4, 3, 7, 2, 7, 7, 4, 7, 1, 4, 3, 7, 3, 4, 5, 1, 5, 5, 1, 5, 6, 3, 4, 3, 1, 1, 1, 5, 7, 2, 2, 6, 3, 6, 1, 1, 6, 5, 4]
>>> unique_count
defaultdict(<functools.partial object at 0x1026c5788>, {'kiwi': 4, 'apple': 1, 'cherry': 5, 'pear': 2, 'pineapple': 6, 'melon': 7, 'banana': 3})
Run Code Online (Sandbox Code Playgroud)