删除空的嵌套列表-Python [英] Remove empty nested lists - Python

查看:39
本文介绍了删除空的嵌套列表-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将.csv文件读取到列表中,并在其中添加了一个空列表,我正在使用下面的代码来做到这一点.

I'm reading in a .csv file to a list and it appends an empty lists, I'm using the code below to do this.

with open('Scores.csv', 'r') as scores:
    reader = csv.reader(scores)
    tscores = [[str(e) for e in r] for r in reader]

它正确地创建了一个嵌套列表的列表,但是在每行读入后都添加一个空列表,如下所示:

It creates a list of nested lists correctly but appends an empty list after every row read in like so:

[[score1, name1], [], [score2, name2], []]

我相信它将 \ n 读为空字符串,这就是为什么要这样做,所以我尝试使用以下方法删除空列表:

I believe it's reading \n as an empty string which is why I'm getting that, so I tried to remove empty lists using:

tscores = [tscores.remove(x) for x in tscores if x]

确实删除了空的嵌套列表,但是将包含数据的所有其他嵌套列表设置为 None ,即 [None,None] .我修改为:

which does delete empty nested lists, but it sets all other nested lists that contained data to None i.e. [None, None]. I modified to:

tscores = [tscores.remove(x) for x in tscores if []]

会完全清除所有嵌套列表.

which wipes out all nested lists completely.

如何在不附加空白列表的情况下读取具有相同输出(嵌套列表列表)的文件,或者在读取后如何删除所有空白列表?

How can I read the file with the same output (a list of nested lists) without appending empty lists or how can I remove all empty lists after being read in?

推荐答案

我认为您想要做的是

tscores = [x for x in tscores if x != []]

只列出 tscores 中的非空列表

which make a list of only the none empty lists in tscores

这篇关于删除空的嵌套列表-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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