Finding elements not in a list

前端 未结 10 632
一向
一向 2020-11-27 13:29

So heres my code:

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<

相关标签:
10条回答
  • 2020-11-27 14:13

    You are reassigning item to the values in z as you iterate through z. So the first time in your for loop, item = 0, next item = 1, etc... You are never checking one list against the other.

    To do it very explicitly:

    >>> item = [0,1,2,3,4,5,6,7,8,9]
    >>> z = [0,1,2,3,4,5,6,7]
    >>> 
    >>> for elem in item:
    ...   if elem not in z:
    ...     print elem
    ... 
    8
    9
    
    0 讨论(0)
  • 2020-11-27 14:16
    list1 = [1,2,3,4]; list2 = [0,3,3,6]
    
    print set(list2) - set(list1)
    
    0 讨论(0)
  • 2020-11-27 14:17
    >> items = [1,2,3,4]
    >> Z = [3,4,5,6]
    
    >> print list(set(items)-set(Z))
    [1, 2]
    
    0 讨论(0)
  • 2020-11-27 14:17

    Your code is a no-op. By the definition of the loop, "item" has to be in Z. A "For ... in" loop in Python means "Loop though the list called 'z', each time you loop, give me the next item in the list, and call it 'item'"

    http://docs.python.org/tutorial/controlflow.html#for-statements

    I think your confusion arises from the fact that you're using the variable name "item" twice, to mean two different things.

    0 讨论(0)
提交回复
热议问题