如何获取删除2D列表的第一个重复值?

时间:2018-09-16 08:34:38

标签: python arrays python-3.x

我在python中有一个2D数组,如下所示:

[[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0], 
[13.38, 5.78, 19.94, 5.76, 19.96, 11.28, 13.4, 11.3], 
[6.72, 5.78, 13.28, 5.76, 13.3, 11.28, 6.74, 11.3],
[0.06, 5.78, 6.6, 5.76, 6.64, 11.28, 0.08, 11.3], 
[13.38, 0.16, 19.94, 0.14, 19.96, 5.66, 13.42, 5.68], 
[6.72, 0.16, 13.28, 0.14, 13.3, 5.64, 6.74, 5.68],
[0.04, 0.18, 6.62, 0.14, 6.64, 5.64, 0.08, 5.68],
[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0]]   

[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0]是重复的数组。
 我要删除第一个重复值并保留最后一个值。
所以我的输出应该是:

[[13.38, 5.78, 19.94, 5.76, 19.96, 11.28, 13.4, 11.3], 
[6.72, 5.78, 13.28, 5.76, 13.3, 11.28, 6.74, 11.3],
[0.06, 5.78, 6.6, 5.76, 6.64, 11.28, 0.08, 11.3], 
[13.38, 0.16, 19.94, 0.14, 19.96, 5.66, 13.42, 5.68], 
[6.72, 0.16, 13.28, 0.14, 13.3, 5.64, 6.74, 5.68],
[0.04, 0.18, 6.62, 0.14, 6.64, 5.64, 0.08, 5.68],
[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0]]  

任何想法该怎么做?

谢谢

3 个答案:

答案 0 :(得分:2)

一种方法是使用pandas模块:

import numpy as np
your_array=np.array([[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0], 
[13.38, 5.78, 19.94, 5.76, 19.96, 11.28, 13.4, 11.3], 
[6.72, 5.78, 13.28, 5.76, 13.3, 11.28, 6.74, 11.3],
[0.06, 5.78, 6.6, 5.76, 6.64, 11.28, 0.08, 11.3], 
[13.38, 0.16, 19.94, 0.14, 19.96, 5.66, 13.42, 5.68], 
[6.72, 0.16, 13.28, 0.14, 13.3, 5.64, 6.74, 5.68],
[0.04, 0.18, 6.62, 0.14, 6.64, 5.64, 0.08, 5.68],
[0.0, 0.0, 0.0, 11.36, 20.0, 11.36, 20.02, 0.0]])

要删除重复项,请使用:

import pandas as pd
df = pd.DataFrame(your_array)
df_without_duplicates = df.drop_duplicates(keep='last')

如果您希望将numpy数组用作输出,请使用:

new_array = df_without_duplicates.values

输出:

array([[13.38,  5.78, 19.94,  5.76, 19.96, 11.28, 13.4 , 11.3 ],
   [ 6.72,  5.78, 13.28,  5.76, 13.3 , 11.28,  6.74, 11.3 ],
   [ 0.06,  5.78,  6.6 ,  5.76,  6.64, 11.28,  0.08, 11.3 ],
   [13.38,  0.16, 19.94,  0.14, 19.96,  5.66, 13.42,  5.68],
   [ 6.72,  0.16, 13.28,  0.14, 13.3 ,  5.64,  6.74,  5.68],
   [ 0.04,  0.18,  6.62,  0.14,  6.64,  5.64,  0.08,  5.68],
   [ 0.  ,  0.  ,  0.  , 11.36, 20.  , 11.36, 20.02,  0.  ]])

答案 1 :(得分:1)

尝试以下操作:首先,您必须反转列表以保留最后一个元素,然后进行简单的for循环将避免重复。最后,再次反转列表以得到所需的输出。

# l is your list

l.reverse()
res = []
for x in l:
    if x not in res:
        res.append(x)
res.reverse()

答案 2 :(得分:1)

这可能是另一种解决方案。反复删除重复列表。

x,y = 0,0
while x < len(l):
    y = x + 1
    while y < len(l):
        if l[y] == l[x]:
            l.pop(x)
            x = 0
            break
        y += 1
    else:
         x += 1