从 Python 中的数组中删除空元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19875595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:50:59  来源:igfitidea点击:

Removing empty elements from an array in Python

pythonarraysfileelements

提问by adampski

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.

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

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

空列表显示为['']- 正如您在第四行看到的那样,我试图明确地将它们去掉。空元素曾经用换行符填充,这些已使用.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.

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

采纳答案by Games Brainiac

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 filterwith Noneor bool:

您也可以使用filterwithNonebool

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