Python如何把两个列表相减呢?
问题描述
有1个有序日期列表A[’2016-01-01’,’2016-01-02’,’2016-01-03’,....’2017-06-01’]和1个无序的但是是需要排除的日期的列表B[’2016-03-02’,’2016-03-08’,]希望把A中的包含的B元素全部去除掉,下面的写法可有不妥?
for x in B: A.remove(x)
问题解答
回答1:A = [item for item in A if item not in set(B)]回答2:
a = [’2016-01-01’,’2016-01-02’,’2016-01-03’,’2017-06-01’, ’2016-03-08’]b = [’2016-03-02’,’2016-03-08’,]print set(a) - set(b)回答3:
看你需求吧,没啥毛病,数据也不是很多, 我提供一种方案
from collections import OrderedDictd_set = OrderedDict.fromkeys(A)for x in B: del d_set[x]A = d_set.keys()回答4:
这种写法会报错,如果x 不在A 中就会报错,这种写法可以先加个 if 判断, x 是否在 A 中再执行 A.remove(x)
试试这个简单的写法:
#coding=utf-8A = [’2016-01-01’,’2016-01-02’,’2016-01-03’,’2017-06-01’,’2017-06-01’,’2016-03-08’,’2016-03-08’]B = [’2016-03-02’,’2016-03-08’]C = []for a in A: for b in B:if a == b: break else:C.append(a)print C回答5:
from collections import OrderedDictA = [’2016-01-01’,’2016-01-02’,’2016-01-03’,’2017-06-01’,’2016-03-08’]B = [’2016-03-02’,’2016-03-08’]d_set = OrderedDict.fromkeys(A)for x in B:
if x in A: del d_set[x]
A = d_set.keys()
相关文章: