Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将数组映射为整数_Python - Fatal编程技术网

在python中将数组映射为整数

在python中将数组映射为整数,python,Python,我有一个数组[[0,1,1],[1,0,0],[1,1,0],[0,1,1],[1,0,0],我想得到这个[[0],[1],[2],[0],[1]]-所以我想用唯一的数字指定所有相同的向量 我有一个办法,但它真的很难看,速度很慢,一点都不像蟒蛇。我怎么能做得更像蟒蛇和更好呢 def get_multiclass_list_nodes(y_): _class = 0 prev_list = list() new_y = list() for el in y_:

我有一个数组
[[0,1,1],[1,0,0],[1,1,0],[0,1,1],[1,0,0]
,我想得到这个
[[0],[1],[2],[0],[1]]
-所以我想用唯一的数字指定所有相同的向量

我有一个办法,但它真的很难看,速度很慢,一点都不像蟒蛇。我怎么能做得更像蟒蛇和更好呢

def get_multiclass_list_nodes(y_):
    _class = 0
    prev_list = list()
    new_y = list()
    for el in y_:
        el = el.astype('int32').tolist()
        if el in prev_list:
            index = -1
            for i, val in enumerate(prev_list):
                if val == el:
                    index = i + 1
                    break
            new_y.append([index])
        else:
            _class += 1
            prev_list.append(el)
            new_y.append([_class])
    return np.array(new_y)

也许这有点滥用numpy,但很简单:

a = np.array([[0, 1, 1], [1, 0, 0], [1, 1, 0], [0, 1, 1], [1, 0, 0]])
lst = [str(x) for x in a]
result = np.unique(lst, return_inverse=True)[1]

也许您想调整最终结果,但从那以后就很简单了。

这应该适合您:

def map_lists_to_ints(list_of_lists):  # Name this better
    tuples = (tuple(l) for l in list_of_lists)

    seen = {}
    next_int = 0
    for tup in tuples:
        if tup not in seen:
            seen[tup] = next_int
            next_int += 1

        yield seen[tup]

list_of_lists = [[0, 1, 1], [1, 0, 0], [1, 1, 0], [0, 1, 1], [1, 0, 0]]

result = list(map_lists_to_ints(list_of_lists))

print(result)

listified_result = [[x] for x in result]

print(listified_result)
输出:

[0, 1, 2, 0, 1]
[[0], [1], [2], [0], [1]]

您真的希望结果是列表列表吗?或者只是一个整数列表?这并不重要,但我想我需要一个列表,因为我不确定sklearn是否可以只使用整数列表。将向量用作字典中的条目,当加载它们时,给每个向量一个唯一的(递增的)数。可以将此数字存储为具有原始向量的元组。