Python|从字符串列表中删除空字符串
在许多场景中,我们会遇到在海量数据中获取空字符串的问题,并且处理有时会成为一项繁琐的任务。让我们讨论一些从字符串列表中删除空字符串的字符串。
方法 #1:使用 remove()
这种特殊的方法非常幼稚,不建议使用,但确实是执行此任务的一种方法。 remove()
通常会删除第一次出现的空字符串,我们会不断迭代这个过程,直到在列表中找不到空字符串。
# Python3 code to demonstrate
# removing empty strings
# using remove()
# initializing list
test_list = ["", "GeeksforGeeks", "", "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 : ['', 'GeeksforGeeks', '', 'is', 'best', '']
Modified list is : ['GeeksforGeeks', 'is', 'best']
方法#2:使用列表理解
删除所有空字符串的更简洁和更好的方法,它只是检查字符串是否不为空,并使用所有不为空的字符串重新创建列表。
# Python 3 code to demonstrate
# removing empty strings
# using list comprehension
# initializing list
test_list = ["", "GeeksforGeeks", "", "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 : ['', 'GeeksforGeeks', '', 'is', 'best', '']
Modified list is : ['GeeksforGeeks', 'is', 'best']
方法 #3:使用join() + split()
结合join()
和split()
操作,也可以完成这个任务。我们首先连接所有字符串,以便删除空白空间,然后将其拆分回列表,以便现在创建的新列表没有空字符串。
# Python3 code to demonstrate
# removing empty strings
# using join() + split()
# initializing list
test_list = ["", "GeeksforGeeks", "", "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 : ['', 'GeeksforGeeks', '', 'is', 'best', '']
Modified list is : ['GeeksforGeeks', 'is', 'best']
方法 #4:使用filter()
使用filter()
是执行此任务的最优雅和最快的方法。强烈推荐这种方法,因为当我们处理可能包含空字符串的大型机器学习数据集时,速度很重要。
# Python 3 code to demonstrate
# removing empty strings
# using filter()
# initializing list
test_list = ["", "GeeksforGeeks", "", "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 : ['', 'GeeksforGeeks', '', 'is', 'best', '']
Modified list is : ['GeeksforGeeks', 'is', 'best']