我有一段我不理解的代码,如果有人可以帮助我,我将不胜感激。
list1 = [48, 33, 46, 46, 87, 11, 50, 99, 65, 87]
list2 = [48, 33, 46]
duplicates = [list1.pop(list1.index(i)) for i in list1 if i in list2]
答案 0 :(得分:4)
我认为您的代码不符合您的要求:
您想要找到list1
中的哪些元素也在list2
中。结果应为[48, 33, 46]
,但结果为[48, 46]
。
这是因为在找到48
副本后,48
会从list1
中删除。在此过程中,33
的索引从1
更改为0
。这意味着for
无法迭代此元素,因为它现在想要从索引1
进行迭代。所以错过了33
。
正确的代码是:
list1 = [48, 33, 46, 46, 87, 11, 50, 99, 65, 87]
list2 = [48, 33, 46]
# duplicates = [list1.pop(list1.index(i)) for i in list1 if i in list2]
duplicates = list(set([i for i in list1 if i in list2]))
print duplicates
这里的主要内容是python列表理解。
解释新的代码逻辑:
1. iterate 1st element of `list1` and find it in `list2`, so pick it. 2. repeat step 1 3. finally you get [48, 33, 46, 46], use `set` to change to [48, 33, 46], and use `list` to chanage back to list
您的旧代码逻辑:
1. iterate 1st element of `list1` and find it in `list2`, so pick it. 2. after pick it, you get the index of 1st element, then pop it (delete it from `list1` and return the element) so for this iterate, you get `48` 3. then you want to iterate 2rd element of `list1`, that supposed to be `33`; however, during the process of step2, you delete the `48`, so `33` becomes the 1st element, nolonger the 2rd element, so when you iterate, you missed the `33` & directly iterate to the `46` 4. for these not in `list2`, will not be handled.