Python如何把兩個(gè)列表相減呢?
問(wèn)題描述
有1個(gè)有序日期列表A[’2016-01-01’,’2016-01-02’,’2016-01-03’,....’2017-06-01’]和1個(gè)無(wú)序的但是是需要排除的日期的列表B[’2016-03-02’,’2016-03-08’,]希望把A中的包含的B元素全部去除掉,下面的寫(xiě)法可有不妥?
for x in B: A.remove(x)
問(wèn)題解答
回答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:
看你需求吧,沒(méi)啥毛病,數(shù)據(jù)也不是很多, 我提供一種方案
from collections import OrderedDictd_set = OrderedDict.fromkeys(A)for x in B: del d_set[x]A = d_set.keys()回答4:
這種寫(xiě)法會(huì)報(bào)錯(cuò),如果x 不在A 中就會(huì)報(bào)錯(cuò),這種寫(xiě)法可以先加個(gè) if 判斷, x 是否在 A 中再執(zhí)行 A.remove(x)
試試這個(gè)簡(jiǎn)單的寫(xiě)法:
#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()
相關(guān)文章:
1. 運(yùn)行python程序時(shí)出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯(cuò)誤?2. 利用IPMI遠(yuǎn)程安裝centos報(bào)錯(cuò)!3. html5和Flash對(duì)抗是什么情況?4. javascript - QQ第三方登錄的問(wèn)題5. 在mac下出現(xiàn)了兩個(gè)docker環(huán)境6. node.js - mongodb查找子對(duì)象的名稱(chēng)為某個(gè)值的對(duì)象的方法7. 測(cè)試自動(dòng)化html元素選擇器元素ID或DataAttribute [關(guān)閉]8. spring-mvc - spring-session-redis HttpSessionListener失效9. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統(tǒng)有創(chuàng)建日志文件,不寫(xiě)入日志信息。10. 淺談Vue使用Cascader級(jí)聯(lián)選擇器數(shù)據(jù)回顯中的坑

網(wǎng)公網(wǎng)安備