在包含数组的python列表中查找重复项

我有一个名为 python 的列表added,它包含 156 个单独的列表,其中包含两个 cols 引用和一个数组。示例如下:


[0, 1, array]

问题是我有重复项,尽管它们并不准确,因为列引用将被翻转。以下两个将完全相同:


[[0, 1, array], [1, 0, array]]

我尝试删除重复项的方法是对数字进行排序并检查是否有相同的数字,如果相同则将结果附加到新列表中。


两者都导致了不同的错误:


for a in range(len(added)):

    added[a][0:2] = added[a][0:2].sort()


TypeError: can only assign an iterable

我还尝试查看该数组是否在我的空 python 列表中no_dups,如果不在,则附加列引用和数组。:


no_dups = []

for a in range(len(added)):

    if added[a][2] in no_dups:

        print('already appended')

    else:

        no_dups.append(added[a])


<input>:2: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.

都没有用。我正在努力思考如何在这里删除重复项。


富国沪深
浏览 111回答 3
3回答

墨色风雨

您的第一个错误是因为list.sort()就地排序所以它不会返回,因此无法分配。解决方法:for a in range(len(added)):&nbsp; &nbsp; added[a][:2] = sorted(added[a][:2])然后,您可以获得唯一索引:unique, idx = np.unique([a[:2] for a in added], axis=0, return_index=True)no_dups = [added[i] for i in idx]len(added)>>> 156len(no_dups)>>> 78

至尊宝的传说

至于TypeError: can only assign an iterable:added[a][0:2].sort()返回None,因此,您不能将其分配给列表。如果你想要列表,你需要使用sorted()实际返回排序列表的方法:added[a][0:2] = sorted(added[a][0:2])至于<input>:2: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.:这是警告而不是错误。尽管如此,这对您不起作用,因为作为警告状态,您的对象数组没有明确定义=。因此,当您搜索 时if added[a][2] in no_dups,它无法真正与added[a][2]的元素进行比较no_dups,因为没有适当地定义相等性。如果它是 numpy 数组,你可以使用:for a in range(len(added)):&nbsp; &nbsp; added[a][0:2] = sorted(added[a][0:2])no_dups = []for a in added:&nbsp; &nbsp; add_flag = True&nbsp; &nbsp; for b in no_dups:&nbsp; &nbsp; &nbsp; &nbsp; #to compare lists, compare first two elements using lists and compare array using .all()&nbsp; &nbsp; &nbsp; &nbsp; if (a[0:2]==b[0:2]) and ((a[2]==b[2]).all()):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print('already appended')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; add_flag = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; if add_flag:&nbsp; &nbsp; &nbsp; &nbsp; no_dups.append(a)len(no_dups):&nbsp; 78len(added):&nbsp; &nbsp;156但是,如果所有数组的长度都相同,则应使用速度明显更快的 numpy 堆叠

回首忆惘然

您可以将整个 added 转换为一个 numpy 数组,然后对索引进行切片并对其进行排序,然后使用 np.unique 获取唯一行。#dummy added in the form [[a,b,array],[a,b,array],...]added = [np.random.choice(5,2).tolist()+[np.random.randint(10, size=(1,5))] for i in range(156)]# Convert to numpyadded_np = np.array(added)vals, idxs = np.unique(np.sort(added_np[:,:2], axis = 1).astype('int'), axis=0, return_index= True)added_no_duplicate = added_np[idxs].tolist()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python