python - 删除字符串列表中包含特定字符串的元素

标签 python string list

我有一个程序创建这样的列表:

["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/

相关文章:

python - 为什么我的 LRU 缓存未命中相同的参数?

python - 自动启动PYTHON脚本

c# - C# 是否提供等同于 '\n' 来表示分页符?

c++ - 使用带有字符串的 find_first_of 而不是 C++ 中的一组预定义字符

python - 查找列表中项目的平均长度。 Python

java - Java 中的类型 List 与类型 ArrayList

r - 奇怪的括号赋值调用 ('[<-' ) 和矩阵参数

python - scipy.stats.ttest_1samp 的基于排列的替代方案

python - 如何使用电缆将信号从 ESP32 发送到 Raspberry pi

ios - 使用 swift 3 将字符串从开始位置剪切到结束位置