搜索一个字符串列表中的所有字符串项

2024-10-04 05:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试确定search字符串的所有元素是否都存在于列表look here字符串中的一个字符串中。出于效率考虑,如果一个元素不存在,则从列表中删除该单词

search_string = '1abc'
look_here_string = ['dedakloera', 'tuau', '1abcdefg']
x = 0
counter = 0

for item in search_string:
    item = search_string[counter]
    #print item, search_string, look_here_string[x]
    if not item in look_here_string[x]:
        print item, 'not in', look_here_string[x]
        look_here_string.remove(look_here_string[x])
        counter = 0
    else:
        print item, 'in', look_here_string[x]
        counter +=1

这是我想要的输出:

1 not in dedakloera    
1 not in tuau          
1 in 1abcdefg          
a in 1abcdefg          
b in 1abcdefg          
c in 1abcdefg

这是我得到的结果:

1 not in dedakloera    #correct
1 not in tuau          #correct
1 in 1abcdefg          #correct
a in 1abcdefg          #correct

脚本似乎过早停止,但我无法找出代码中的错误。非常感谢您的帮助


Tags: 字符串in元素列表searchstringherecounter
2条回答

更简单的方法是遍历外循环中的look_here_string

search_string = '1abc'
look_here_string = ['dedakloera', 'tuau', '1abcdefg']
ind_to_remove = []
for i,s in enumerate(look_here_string):
    for e in search_string:
        if not e in s:
            ind_to_remove.append(i)
            print e, 'not in', s
            break
        else:
            print e, 'in', s
for i in ind_to_remove[::-1]:
    del look_here_string[i]

您可以使用“all”内置函数和列表理解更简洁地编写:

>>> search_string = '1abc'
>>> look_here_string = ['dedakloera', 'tuau', '1abcdefg']
>>> [string for string in look_here_string 
            if all(char in string for char in search_string)]

这将创建一个新列表,但它将自动筛选无效字符串

相关问题 更多 >