python - 在 Python 中标记列表的任何快速方法?

标签 python list dictionary

我有一个包含 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() objectitertools.count() object装配成作为工厂产生下一个值(value);这将避免必须自己测试每个键以及必须手动递增。

然后使用列表理解将这些数字放入列表中:

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() callablenext() function 周围创建一个包装器, 以确保代码在 Python 2 或 Python 3 中工作。

我在这里使用了一个整数计数,从 1 开始。如果您坚持使用浮点值,则可以将 count(1) 替换为 count(1.0);你会得到 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})

关于python - 在 Python 中标记列表的任何快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697179/

相关文章:

python - Twisted 中的高级事件处理

python - 使用切片的数组赋值

list - 从现有的json列表中提取唯一值以创建唯一的listview构建器

python - 使用 dict 和 map 在 Dataframe 中创建新列只给出 NaN

python - 根据另一个键过滤字典列表以删除键中的重复项

python - 如何在 Python 中组合两个列表的每个元素?

python - 是否有任何指南可用于从 Python 2.6 开始编写 Python 以编写将来可轻松迁移到 Python 3 的应用程序?

python - 是否有可用于 python 覆盖工具的 python 版本特定 "#pragma nocover"?

c# - 子列表的补充列表

python - 如何根据特定位置的类似项目排列列表