在Python中从数组中删除空元素 [英] Removing empty elements from an array in Python

查看:2820
本文介绍了在Python中从数组中删除空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

with open("text.txt", 'r') as file:
    for line in file:
        line = line.rstrip('\n' + '').split(':')
        print(line)

我在尝试删除正在生成的一系列数组中的空列表时遇到麻烦。我想将每一行都做成 text.txt 中的数组,这样我就能准确地分别访问每一行的每个元素。

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.

空白列表显示为 [''] -如第四行所示,我试图明确地将它们删除。空元素曾经用换行符填充,可使用 .rstrip('\n')成功删除。

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').

编辑:

我对某些术语有误解,以上内容现已更新。本质上,我想摆脱空列表。

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']

您也可以将过滤器 None 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中从数组中删除空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆