Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pythonic删除空元素嵌套列表的方法和时间_Python_Python 3.x_List - Fatal编程技术网

Pythonic删除空元素嵌套列表的方法和时间

Pythonic删除空元素嵌套列表的方法和时间,python,python-3.x,list,Python,Python 3.x,List,我尝试了不同的方法将空元素删除到嵌套列表中,但我不知道是否是100k列表中最好的方法 例如: tag = [['A', 'B', 'C', ''], ['D', 'F', 'G', '', '',''], ['H','I','J'],['L','M','','','','']] 我发现不同的方法如下: list(filter(None, tag)) 或 或 没办法,我不能删除空元素,第一,第二,实现它的时间太慢了。 我还尝试在python tutor上开发一些嵌套列表,但不删除任何内容 请提

我尝试了不同的方法将空元素删除到嵌套列表中,但我不知道是否是100k列表中最好的方法

例如:

tag = [['A', 'B', 'C', ''], ['D', 'F', 'G', '', '',''], ['H','I','J'],['L','M','','','','']]
我发现不同的方法如下:

list(filter(None, tag))

没办法,我不能删除空元素,第一,第二,实现它的时间太慢了。 我还尝试在python tutor上开发一些嵌套列表,但不删除任何内容

请提个建议好吗?
谢谢

我不知道性能是否令人满意,但是

tags = [['A', 'B', 'C', ''], ['D', 'F', 'G', '', '',''],
        ['H','I','J'],['L','M','','','','']]
filtered_tags = [[tag for tag in item if tag] for item in tags]
print(filtered_tags)
输出

[['A', 'B', 'C'], ['D', 'F', 'G'], ['H', 'I', 'J'], ['L', 'M']]

您可以在列表理解中使用
过滤器

[list(filter(None,l)) for l in tag]
# [['A', 'B', 'C'], ['D', 'F', 'G'], ['H', 'I', 'J'], ['L', 'M']]

使用Python3.7Windows10进行一些timeit分析

#Using list of size 100_000 i.e len(tag)=100_000 for benchmarking
In [12]: timeit [list(filter(None,l)) for l in tag]
42.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [13]: timeit [[i for i in l if i] for l in tag]
34.7 ms ± 733 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

拜托,波斯特。我打赌这个问题以前被问过一百万次=>bingoYes当然,一百万次,但不是性能。无论如何,谢谢你!
[list(filter(None,l)) for l in tag]
# [['A', 'B', 'C'], ['D', 'F', 'G'], ['H', 'I', 'J'], ['L', 'M']]
[[i for i in l if i] for l in tag]
# [['A', 'B', 'C'], ['D', 'F', 'G'], ['H', 'I', 'J'], ['L', 'M']]
#Using list of size 100_000 i.e len(tag)=100_000 for benchmarking
In [12]: timeit [list(filter(None,l)) for l in tag]
42.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [13]: timeit [[i for i in l if i] for l in tag]
34.7 ms ± 733 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)