在许多情况下, 我们会遇到在大量数据中获取空字符串并处理有时变得乏味的问题。让我们讨论一些从字符串列表中删除空字符串的方法。
方法1:使用remove()
此特定方法非常幼稚, 不建议使用, 但实际上是执行此任务的方法。去掉()通常会删除第一次出现的空字符串, 并且我们会重复进行此过程, 直到在列表中找不到空字符串为止。
# Python3 code to demonstrate
# removing empty strings
# using remove()
# initializing list
test_list = [" ", " lsbin ", " ", " is ", " best ", " "]
# Printing original list
print ( "Original list is : " + str (test_list))
# using remove() to
# perform removal
while ("" in test_list) :
test_list.remove("")
# Printing modified list
print ( "Modified list is : " + str (test_list))
输出如下:
Original list is : ['', 'lsbin', '', 'is', 'best', '']
Modified list is : ['lsbin', 'is', 'best']
方法2:使用列表理解
更简洁, 更好的方法是删除所有空字符串, 它只是检查字符串是否不为空, 然后使用所有不为空的字符串重新创建列表。
# Python 3 code to demonstrate
# removing empty strings
# using list comprehension
# initializing list
test_list = [" ", " lsbin ", " ", " is ", " best ", " "]
# Printing original list
print ( "Original list is : " + str (test_list))
# using list comprehension to
# perform removal
test_list = [i for i in test_list if i]
# Printing modified list
print ( "Modified list is : " + str (test_list))
输出如下:
Original list is : ['', 'lsbin', '', 'is', 'best', '']
Modified list is : ['lsbin', 'is', 'best']
方法3:使用join() + split()
结合join()和split()操作,也可以实现此任务。我们首先连接所有的字符串以删除空字符串,然后将其分割回列表,这样创建的新列表中就没有空字符串了。
# Python3 code to demonstrate
# removing empty strings
# using join() + split()
# initializing list
test_list = [" ", " lsbin ", " ", " is ", " best ", " "]
# Printing original list
print ( "Original list is : " + str (test_list))
# using join() + split() to
# perform removal
test_list = ' ' .join(test_list).split()
# Printing modified list
print ( "Modified list is : " + str (test_list))
输出如下:
Original list is : ['', 'lsbin', '', 'is', 'best', '']
Modified list is : ['lsbin', 'is', 'best']
方法4:使用filter()
使用filter()是执行此任务的最优雅和最快的方法。这种方法是强烈推荐的,因为当我们处理可能包含空字符串的大型机器学习数据集时,速度很重要。
# Python 3 code to demonstrate
# removing empty strings
# using filter()
# initializing list
test_list = [" ", " lsbin ", " ", " is ", " best ", " "]
# Printing original list
print ( "Original list is : " + str (test_list))
# using filter() to
# perform removal
test_list = list ( filter ( None , test_list))
# Printing modified list
print ( "Modified list is : " + str (test_list))
输出如下:
Original list is : ['', 'lsbin', '', 'is', 'best', '']
Modified list is : ['lsbin', 'is', 'best']
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。