如何在这里使用.pop和.index?

问题描述 投票:0回答:2

我有一段我不理解的代码,如果有人可以帮助我,我将不胜感激。

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]
python list indexing pop
2个回答
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.

1
投票

逐步介绍它,它可能有意义:

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中删除该索引处的项目

© www.soinside.com 2019 - 2024. All rights reserved.