python在空列表中输入元素_Python从列表列表中删除空元素

1586010002-jmsa.png

I have a list of lists like this:

[['A001', 'atendimento', 'sust', 'concessionário', 'adv', 'bom', 'adj', '', ''],

['A001', 'falar', 'verb', 'ter', 'verb', 'nada', 'pron', 'carro', 'sust', '', ''],

['A001', 'não', 'adv', 'perguntar', 'verb', 'problema', 'sust', 'carro', 'sust', '', ''],

['A001', 'não', 'adv', 'oferecer', 'verb', 'ligar', 'verb', 'compra', 'sust', '', ''],

['A001', 'não', 'adv', 'oferecer', 'verb', 'serviço', 'sust', 'compra', 'sust', '', '']]

And I want to remove empty elements from each list getting a new list of lists without the empty elements:

[['A001', 'atendimento', 'sust', 'concessionário', 'adv', 'bom', 'adj'],

['A001', 'falar', 'verb', 'ter', 'verb', 'nada', 'pron', 'carro', 'sust'],

['A001', 'não', 'adv', 'perguntar', 'verb', 'problema', 'sust', 'carro', 'sust'],

['A001', 'não', 'adv', 'oferecer', 'verb', 'ligar', 'verb', 'compra', 'sust'],

['A001', 'não', 'adv', 'oferecer', 'verb', 'serviço', 'sust', 'compra', 'sust']]

How could I achieve this?

I tried this:

str_list = filter(None, list_of_lists)

解决方案

Your attempt will remove empty lists from the list of lists, not empty elements from the sublists. Instead, apply the filter to the sublists:

str_list = [list(filter(None, lst)) for lst in list_of_lists]

The call to filter() is wrapped with list() in case you happen to try this in python3 later, as filter() returns an iterator in py3.

Note that since you tagged this as csv you might have to be careful as filtering might produce rows with differing lengths and items in wrong columns. If you know that for each row the 2 last items will always be empty, you could slice them out:

str_list = [row[:-2] for row in list_of_lists]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值