英文:
How to get the arrays not contained in another array?
问题
first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]
# 返回第一个数组中不在第二个数组中的元素
def difference(arr1, arr2):
result = [item for item in arr1 if item not in arr2]
return result
# 调用函数并输出结果
difference(first, second)
# 返回 [[0, 12], [0, 13]]
英文:
I have two Python arrays with arrays inside:
first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]
and I want to get as a result the array that is in the first one, but not in the other:
difference(first,second)
#returns [[0,12],[0,13]]
right now they are numpy arrays, but a solution with regular ones is also valid.
I tried using np.setdiff1d
but it returned an array with the exclusive ints, not exclusive arrays.
And I tried to iterate through the second array deleting its elements from the first one:
diff = first.view()
for equal in second:
diff = np.delete(diff, np.where(diff == equal))
but it returned similar not useful results
答案1
得分: 1
你可以使用普通的 Python 列表(而不是 numpy 数组)和简单的列表推导来完成这个任务:
diff = [lst for lst in first if lst not in second]
diff
[[0, 12], [0, 13]]
英文:
You could do this with regular old Python lists (not numpy arrays) and a simple list comprehension:
>>> diff = [lst for lst in first if lst not in second]
>>> diff
[[0, 12], [0, 13]]
答案2
得分: 0
使用NumPy,您可以进行广播以比较元素,并使用np.all / np.any将比较结果合并到掩码中:
import numpy as np
first = np.array([[0,10],[0,11],[0,12],[0,13]])
second = np.array([[0,10],[0,11],[1,7]])
mask = ~np.any(np.all(first[:,None]==second,axis=-1),axis=-1)
print(first[mask])
[[ 0 12]
[ 0 13]]
英文:
Using numpy, you can broadcast to compare the elements and use np.all/np.any to consolidate the comparison results into a mask:
import numpy as np
first = np.array([[0,10],[0,11],[0,12],[0,13]])
second = np.array([[0,10],[0,11],[1,7]])
mask = ~np.any(np.all(first[:,None]==second,axis=-1),axis=-1)
print(first[mask])
[[ 0 12]
[ 0 13]]
答案3
得分: -1
如果我理解正确,您需要一个函数,请尝试这个:
first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]
def difference(first, second): # 声明函数
lst = [] # 声明列表
for i in first: # 循环运行
if i not in second:
lst.append(i) # 仅记住这种方法
return lst # 此函数的输出 'lst'
difference(first, second)
我不确定这是否是最佳选项,但从您的提问方式来看,这种方法适合您。
英文:
If I understand correctly, you need a function, try this:
first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]
def difference(first,second): #declare function
lst = [] #declare list
for i in first: #run loop
if i not in second: lst.append(i) #just remember method
return(lst) #output of this function 'lst'
difference(first,second)
I'm not sure if this is the best option, but looking by the way you ask, this method is for you
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论