假设有一个list,list1=【2,0,1,0,0,0,0,1,0,5,0,0】现在要把数据是0的删除。保留非0数据并保存。
一般做法是:
list1 =[2, 0, 1, 0, 0, 0, 0,1,0,5,0,0] i=0 list2=[] b=len(list1) while b-i > 0: if list1[i]!=0: list2.append(list1[i]) i+=1 print(list2)加强版:
list1 =[2, 0, 1, 0, 0, 0, 0,1,0,5,0,0] list2=filter(lambda x: x > 0, list1) print(list(list2))进化版(考虑迭代器)
list1 =[2, 0, 1, 0, 0, 0, 0,1,0,5,0,0] list2=[x for x in list1 if x>0] print(list2)