python删除列表中空字符

一、目的

近期,处理数据中遇到了删除列表中空字符的需求。

# -*- coding:utf-8 -*-
'''
目的:删除None和''
'''

二、数据

table1=[['地区', None, None, '公司名称', '', '注册资本', '', '成立时间', '银监会批复时间'], [None, None, None, None, None, '(亿元)', None, None, None], ['', '福建', '', '福建省闽投资产管理有限公司', '15', None, None, '2008年11月', '2014年11月'],  ['', '西藏', '', '海徳资产管理有限公司', '47.21', '2016年7月', '2016年10月'], ['', '新疆', '', '新疆金投资产管理股份有限公司', '10', '2017年8月', '2018年3月'], ['', '云南', '', '云南省资产管理有限公司', '20', '2016年12月', '2017年4月']]

数据中包含了None和",都要删除。

三、处理

方法1 remove

#method 1:
for i in table1:
    while None in i:
        i.remove(None)
    while '' in i:
        i.remove('')    
print(table1)

 

 方法2

#method 2:
table2=[]
for i in table1:
    i = [x for x in i if x !='' and x !=None]
    print(i)
    table2.append(i)
print(table2)

 

方法3 filter函数

#method3:
table2=[]
for i in table1:
    a=list(filter(None,i))
    print(a)
    table2.append(i)
print(table2)

 

方法4 定义函数+filter函数

#method4:
table2=[]
def not_empty(s):
	return s and s.strip() #还删除了空格
for i in table1:
    a=list(filter(not_empty,i))
    table2.append(a)
print(table2)

 

[['地区', '公司名称', '注册资本', '成立时间', '银监会批复时间'], ['(亿元)'], ['福建', '福建省闽投资产管理有限公司', '15', '2008年11月', '2014年11月'], ['西藏', '海徳资产管理有限公司', '47.21', '2016年7月', '2016年10月'], ['新疆', '新疆金投资产管理股份有限公司', '10', '2017年8月', '2018年3月'], ['云南', '云南省资产管理有限公司', '20', '2016年12月', '2017年4月']]
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值