python - 如何为项目列表创建标签列表?

标签 python algorithm list numpy

我想知道以下是否可以做得更好:

import numpy as np
def label_items(items):
    data = np.array(items)
    labels = np.zeros(len(items), dtype='int')
    for label, value in enumerate(set(items)):
        labels[data==value] = label
    return labels

例如:

label_items(['a', 'a', 'c', 'd', 'e', 'b', 'e', 'e', 'd', 'c'])

会回来

array([0, 0, 1, 4, 3, 2, 3, 3, 4, 1])

附录:字母只是一个例子,它可以是任何东西的列表。这就是我将函数称为“label_items”的原因。标签的顺序无关紧要。

最佳答案

如果顺序不重要,可以使用numpy.unique :

import numpy as np

def label_items(arr):
    return np.unique(arr, return_inverse=True)

vals, labels = label_items(['a', 'a', 'c', 'd', 'e', 'b', 'e', 'e', 'd', 'c'])

print(vals)

['a' 'b' 'c' 'd' 'e']

print(labels)

[0 0 2 3 4 1 4 4 3 2]

关于python - 如何为项目列表创建标签列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51893702/

相关文章:

algorithm - 函数式语言的快速元素查找(Haskell)

python - 如何计算二维矩阵之间的距离

r - 观星者在摘要列表上

python - 从字符串中提取二维列表

包含变量的 Python 属性名称

Python ggplot 问题绘制 >8 只股票和图例被截断

python - numpy ndarray 中匹配行之间的余弦相似度

python - 从特定 channel 抓取 YouTube 视频并进行搜索?

java - 排序数组与哈希表 : Which data structure would be more efficient in searching over a range of dates in a calendar app?

list - 从方案中的列表中删除负值