我有一段我不理解的代码,如果有人可以帮助我,我将不胜感激。
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]
我相信您的代码不符合您的要求:
你想找到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.
逐步介绍它,它可能有意义:
for i in list1 if i in list2
应该有意义;它相当于
for i in list1:
if i in list2:
...
list1.index(i)
得到i
的索引(在list1
中找到的list2
中的每个元素),最后list1.pop
从list1中删除该索引处的项目