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

你可能感兴趣的:(python删除列表空元素)