我有一个程序创建这样的列表:
["abc a","hello","abc","hello z"]
我的目标是在列表中移动,如果该元素包含在字符串之一中,则删除该字符串
第一次迭代:
# abc a can't be found in any other element:
["abc a","hello","abc","hello z"]
第二个:
# hello is present in element 4:
["abc a","hello","abc"]
第三个:
# abc can be found in element one:
["hello","abc"]
我尝试使用filter()函数但没有成功
我希望每个元素都传入函数中,唯一的问题是列表大小正在减小,因此这是我不知道如何处理的另一个问题
谢谢
最佳答案
您最初可以做的是,当您获取列表时,将其设置为[[element1,status],[element2,status]]。此处状态将显示或删除。 最初,所有状态都将存在,当您遍历而不是删除/删除元素时,只需将状态更新为已删除,并且在每次迭代中,如果找到匹配项,您只会考虑其状态是否存在,这样您的列表大小保持不变。最后仅选择那些状态为存在的元素。希望你能明白。
init_list = ["abc a","hello","abc","hello z"]
new_list = list()
for i in init_list:
new_list.append([i,"present"])
for i in new_list:
if i[1] == 'present':
for j in new_list:
if j[1] == 'present' and not i == j:
fin = j[0].find(i[0])
if not fin == -1:
j[1] = 'deleted'
fin_list = list()
for i in new_list:
if i[1] == 'present':
fin_list.append(i[0])
print(fin_list)
关于python - 删除字符串列表中包含特定字符串的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57089050/