为每个相同的列表项分配值

时间:2014-10-16 23:16:11

标签: python

我正在写的函数有一个列表列表。我想遍历列表,获取列表中的第一个元素和所有匹配元素,并在相同位置的另一个数组中指定0。然后是1,依此类推,直到分配了所有元素。

我如何在python中执行此操作?

拿这份清单:

[[0.39999999999999997],
 [2.145454545454545],
 [0.39999999999999997],
 [0.39999999999999997],
 [0.39999999999999997],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545],
 [0.39999999999999997],
 [0.39999999999999997],
 [0.39999999999999997],
 [2.145454545454545],
 [2.145454545454545],
 [2.145454545454545]]

输出[0,1,0,0,0,1,1,1,1,1,1,1,0,0,0,1,1,1]

closestCluster labels:

 [[0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28],
[0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42,
 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.3
2, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0
.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28],
[0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42,
 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.3
2, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0
.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28],
[0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42,
 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.3
2, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0
.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28], [0.18, 0.31, 0.32, 0.42, 0.28],
[0.18, 0.34, 0.71, 0.71, 0.9]]

进入类似的列表。我希望这适用于R ^ n,但是1到4是我的测试数据。

1 个答案:

答案 0 :(得分:1)

如果您正在尝试做我认为您正在尝试做的事情:

lst = ["A","A","B","C","A"]
values = {}

i = 0
for value in lst:
    if value[0] in values: continue
    values[value[0]] = i
    i += 1

lst2 = [values[n[0]] for n in lst]

输出:

>>> print(lst2)
[0, 0, 1, 2, 0]

*根据OP的编辑进行编辑