在列表中查找不包含的元素

95

这是我的代码:

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 包含一组整数。我想将 itemz 进行比较,并打印出与 item 不同的数字。

我可以打印出在比较时属于z而不是item的元素,但是使用上面的代码尝试相反的操作时没有任何输出。

有什么帮助吗?


这回答您的问题吗?获取两个列表之间的差异 - Georgy
12个回答

1
itemz是排序迭代器的情况下,我们可以通过这样做将复杂度从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

如果两者都是迭代器,我们也有机会减少内存占用,不将zexclude_sorted_iterator)存储为列表。

for循环(这是批准的答案)的大O表示法是O(n),而您的答案在for循环中嵌套了一个while循环,因此在您的情况下复杂度将增加到O(n^2) - Muhammad Haseeb Khan

0
如果列表已排序并且您知道检查列表的元素在基本列表中,您可以使用两个指针进行更优化的 O(n) 解决方案(其中 n 将是 base_list 的长度):
base_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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接