python从另一个列表中删除列表中的元素,并且两个列表中都有多个项目 [英] python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both

查看:594
本文介绍了python从另一个列表中删除列表中的元素,并且两个列表中都有多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与以下内容有关:>删除所有元素出现在另一个列表中的一个

我有listA [1, 1, 3, 5, 5, 5, 7]和listB [1, 2, 5, 5, 7],我想从listA中减去出现次数.结果应该是一个新列表:[1, 3, 5] 注意:

I have listA [1, 1, 3, 5, 5, 5, 7] and listB [1, 2, 5, 5, 7] and I want to subtract occurrences of items from listA. The result should be a new list: [1, 3, 5] Note:

  1. 1在listA中出现了2次,在listB中出现了一次,现在出现2-1 = 1次
  2. 2没有出现在listA中,所以什么也没发生
  3. 3停留1次,因为它不在listB中
  4. 5在listA中出现了3次,在listB中出现了2次,所以现在它出现了3-2 = 1次
  5. 7在listA中发生一次,在listB中发生一次,所以现在将出现1-1 = 0次
  1. 1 had 2 occurrences in listA and once in listB, now it appears 2-1=1 times
  2. 2 did not appear in listA, so nothing happens
  3. 3 stays with 1 occurrence, as its not in listB
  4. 5 occurred 3 times in listA and 2 in listB, so now it occurs 3-2=1 times
  5. 7 occurred once in listA and once in listB, so now it will appear 1-1=0 times

这有意义吗?

推荐答案

这是非Python初学者的非列表理解版本

Here is a non list comprehension version for those new to Python

listA = [1, 1, 3, 5, 5, 5, 7]
listB = [1, 2, 5, 5, 7]
for i in listB:
    if i in listA:
        listA.remove(i)

print listA

这篇关于python从另一个列表中删除列表中的元素,并且两个列表中都有多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆