python删除列表空元素_在Python中从数组中删除空元素

1586010002-jmsa.png

with open("text.txt", 'r') as file:

for line in file:

line = line.rstrip('\n' + '').split(':')

print(line)

I am having trouble trying to remove empty lists in the series of arrays that are being generated. I want to make every line an array in text.txt, so I would have the ability to accurately access each element individually, of each line.

The empty lists display themselves as [''] - as you can see by the fourth line, I've tried to explicitly strip them out. The empty elements were once filled with new line characters, these were successfully removed using .rstrip('\n').

Edit:

I have had a misconception with some terminology, the above is now updated. Essentially, I want to get rid of empty lists.

解决方案

Since I can't see your exact line, its hard to give you a solution that matches your requirements perfectly, but if you want to get all the elements in a list that are not empty strings, then you can do this:

>>> l = ["ch", '', '', 'e', '', 'e', 'se']

>>> [var for var in l if var]

Out[4]: ['ch', 'e', 'e', 'se']

You may also use filter with None or bool:

>>> filter(None, l)

Out[5]: ['ch', 'e', 'e', 'se']

>>> filter(bool, l)

Out[6]: ['ch', 'e', 'e', 'se']

If you wish to get rid of lists with empty strings, then for your specific example you can do this:

with open("text.txt", 'r') as file:

for line in file:

line = line.rstrip('\n' + '').split(':')

# If line is just empty

if line != ['']:

print line

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值