Removing empty elements from an array in Python

六眼飞鱼酱① 提交于 2019-12-23 08:35:44

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/19875595/removing-empty-elements-from-an-array-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!