这是我的代码:
item = [0,1,2,3,4,5,6,7,8,9]
z = [] # list of integers
for item in z:
if item not in z:
print item
z
包含一组整数。我想将 item
与 z
进行比较,并打印出与 item
不同的数字。
我可以打印出在比较时属于z
而不是item
的元素,但是使用上面的代码尝试相反的操作时没有任何输出。
有什么帮助吗?
item
和z
是排序迭代器的情况下,我们可以通过这样做将复杂度从O(n^2)
降低到O(n+m)
。def iexclude(sorted_iterator, exclude_sorted_iterator):
next_val = next(exclude_sorted_iterator)
for item in sorted_iterator:
try:
while next_val < item:
next_val = next(exclude_sorted_iterator)
continue
if item == next_val:
continue
except StopIteration:
pass
yield item
z
(exclude_sorted_iterator
)存储为列表。O(n)
,而您的答案在for循环中嵌套了一个while循环,因此在您的情况下复杂度将增加到O(n^2)
。 - Muhammad Haseeb Khanbase_list = [0, 1, 2, 3, 4, 5, 6, 7, 8]
checking_list = [1, 3, 5]
expected_return = [0, 2, 4, 6, 7, 8]
j = 0
i = 0
elements_not_in_checking_list = []
while i < len(base_list):
if j < len(checking_list) and base_list[i] == checking_list[j]:
i += 1
j += 1
else:
elements_not_in_checking_list.append(base_list[i])
i += 1