5 回答
TA贡献1864条经验 获得超2个赞
在 python 中有一个叫做list comprehension的东西,它比长循环结构更有效且更容易阅读for。要创建您要查找的列表,这是列表理解的示例:
result = [s for s in strings if all(sf in s for sf in searching_for)]
# ['how are you doing?', 'are you doing well?']
它按照它所说的那样做,在我看来是直截了当的:
创建一个列表(括号)
s变量中的字符串strings
如果可以找到sf变量的所有字符串searching_fors
TA贡献1794条经验 获得超8个赞
all(or any) 将尝试遍历它的输入;and Trueor False(作为 的结果j in i)不是可迭代的。这是导致TypeError:
all(True)
# TypeError: 'bool' object is not iterable
相反,让你的内循环更简单:
def search(*args):
arg_list = []
search_for = numpy.append(arg_list, args)
for i in strings:
if all(j in i for j in search_for):
print(i)
或者更简单:
def search(args):
for i in strings:
if all(j in i for j in args):
print(i)
输出:
search(searching_for)
# how are you doing?
# are you doing well?
请注意,您不需要all(...) is Truesince allwould already have returned either TrueorFalse
TA贡献1895条经验 获得超7个赞
strings = ['hello everyone!', 'how are you doing?', 'are you doing well?', 'are you okay?', 'good, me too.']
keywords = ['are', 'you', 'doing']
for s in strings:
for word in s.split():
if word in keywords:
print(s)
break
TA贡献1876条经验 获得超7个赞
尝试这个:
for st in strings:
if set(searching_for).issubset(set(st[:-1].split())):
print(st)
TA贡献1783条经验 获得超4个赞
你可以试试
print([i for i in strings if all([s in i for s in searching_for])])
输出
['how are you doing?', 'are you doing well?']
此列表理解将检查searching_for
列表中的所有单词是否在每个句子中strings
,如果是,它将打印该句子。
添加回答
举报