Python|从列表中删除前缀字符串
有时,在处理数据时,我们可能会遇到一个问题,即我们需要过滤字符串列表,以便删除以特定前缀开头的字符串。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + remove() + startswith()
以上功能的组合可以解决这个问题。在此,我们删除以使用循环访问的特定前缀开头的元素并返回修改后的列表。
# Python3 code to demonstrate working of
# Remove prefix strings from list
# using loop + remove() + startswith()
# initialize list
test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# initialize prefix
pref = 'x'
# Remove prefix strings from list
# using loop + remove() + startswith()
for word in test_list[:]:
if word.startswith(pref):
test_list.remove(word)
# printing result
print("List after removal of Kth character of each string : " + str(test_list))
输出 :
The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']
方法#2:使用列表理解+ startswith()
这是可以执行此任务的另一种方式。在这种情况下,我们不会就地执行删除,而是重新创建没有与前缀匹配的元素的列表。
# Python3 code to demonstrate working of
# Remove prefix strings from list
# using list comprehension + startswith()
# initialize list
test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
# printing original list
print("The original list : " + str(test_list))
# initialize prefix
pref = 'x'
# Remove prefix strings from list
# using list comprehension + startswith()
res = [ele for ele in test_list if not ele.startswith(pref)]
# printing result
print("List after removal of Kth character of each string : " + str(res))
输出 :
The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']