【发布时间】:2020-01-29 19:48:39
【问题描述】:
我需要比较 2 个列表并有效地从第二个数组中删除出现在第一个数组中的元素。我的解决方案如下:
自制算法:
#function accepts 2 arrays. Compares elements from 1st array to 2nd to see if they exist in 2nd,
#and removes them from 2nd array.
def compareRemove(self, array1 = [], array2 = []):
#starting iteration values
i = 0
j = 0
array1_length = len(array1)
array2_length = len(array2)
while i < array1_length:
while j < array2_length:
#compare element from first array to second array, remove element if same,
#and update second array length
if array1[i] == array2[j]:
del array2[j]
array2_length = len(array2)
#otherwise move j forward
else:
j = j + 1
#when 2nd while loop is done move i forward and reset j to 0
i = i + 1
j = 0
return array2
对 SO 的研究建议:
updated_file_strings = [x for x in array2 if not x in array1]
两者都同样快,但是随着我的阵列长度增加,两者都会变慢。即使数组长度增加,我是否可以使用任何可以很好地执行的方法?顺序无关紧要。
示例:
array1 = [1, 2, 3]
array2 = [1, 2, 3, 5, 5, 5]
result_array = [5, 5, 5]
应不删除第二个数组中的重复项。
【问题讨论】:
-
请创建一个最小的、可验证的示例和您的预期输出,以便我们更好地帮助您
标签: python