簡體   English   中英

有什么快速的方法可以在Python中標記列表?

[英]Any quick way to labelize a list in Python?

我有20萬個元素的列表。 這些元素是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]

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]

functools.partial()調用可next()函數周圍創建包裝器,以確保代碼可在Python 2或Python 3中工作。

我在這里使用一個整數,從1開始。 如果您堅持使用浮點值,則可以用count(1.0)替換count(1) 你會得到1.02.03.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})
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()]

這樣的事嗎?

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

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

結果- [2, 3, 0, 1, 2, 1] 2,3,0,1,2,1 [2, 3, 0, 1, 2, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM