简体   繁体   中英

Any quick way to labelize a list in Python?

I have a list of 200k elements. Those elements are 7 different labels (it is actually a list of fruit). I need to assign a number to each fruit.

Is there a quick way to do this?

I have written this so far.. and it is taking ages.

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]

Use a collections.defaultdict() object with an itertools.count() object rigged up as to produce a next value as the factory; this'll avoid having to test for each key yourself as well as having to manually increment.

Then use a list comprehension to put those numbers into the list:

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]

The functools.partial() callable creates a wrapper around the next() function , to ensure the code works in either Python 2 or Python 3.

I used an integer count here, starting at 1 . You can replace count(1) with count(1.0) if you insist on having floating point values; you'll get 1.0 , 2.0 , 3.0 , etc. instead.

Demo:

>>> 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})
fruit_list = ['apple', 'banana', 'strawberry', 'watermelon','apple','watermelon']

unique_fruits = [x for x in set(fruit_list)]
fruit_dict = dict((unique_fruits[y],y) for y in range(len(unique_fruits)))
result = [(x, fruit_dict.get(x)) for x in fruit_list if x in fruit_dict.keys()]

Something like that?

Result: [('apple', 2), ('banana', 3), ('strawberry', 0), ('watermelon', 1), ('apple', 2), ('watermelon', 1)]

Or result = [fruit_dict.get(x) for x in fruit_list if x in fruit_dict.keys()]

Result - [2, 3, 0, 1, 2, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM