3 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的第一個(gè)錯(cuò)誤是因?yàn)閘ist.sort()就地排序所以它不會(huì)返回,因此無法分配。解決方法:
for a in range(len(added)):
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)
>>> 156
len(no_dups)
>>> 78

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
至于TypeError: can only assign an iterable:
added[a][0:2].sort()返回None,因此,您不能將其分配給列表。如果你想要列表,你需要使用sorted()實(shí)際返回排序列表的方法:
added[a][0:2] = sorted(added[a][0:2])
至于<input>:2: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.:
這是警告而不是錯(cuò)誤。盡管如此,這對(duì)您不起作用,因?yàn)樽鳛榫鏍顟B(tài),您的對(duì)象數(shù)組沒有明確定義=。因此,當(dāng)您搜索 時(shí)if added[a][2] in no_dups,它無法真正與added[a][2]的元素進(jìn)行比較no_dups,因?yàn)闆]有適當(dāng)?shù)囟x相等性。如果它是 numpy 數(shù)組,你可以使用:
for a in range(len(added)):
added[a][0:2] = sorted(added[a][0:2])
no_dups = []
for a in added:
add_flag = True
for b in no_dups:
#to compare lists, compare first two elements using lists and compare array using .all()
if (a[0:2]==b[0:2]) and ((a[2]==b[2]).all()):
print('already appended')
add_flag = False
break
if add_flag:
no_dups.append(a)
len(no_dups): 78
len(added): 156
但是,如果所有數(shù)組的長(zhǎng)度都相同,則應(yīng)使用速度明顯更快的 numpy 堆疊

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
您可以將整個(gè) added 轉(zhuǎn)換為一個(gè) numpy 數(shù)組,然后對(duì)索引進(jìn)行切片并對(duì)其進(jìn)行排序,然后使用 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 numpy
added_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()
添加回答
舉報(bào)