我试着测试一些单词是否在一个句子中,如下面的代码所示。不幸的是,我想指的是第一个in
:
- 测试句子是否包含x,
- 但我认为它把它当作句子在循环。
如何纠正下面的代码:
非常困惑,在一个新的终端中它工作:
Python 3.8.10 (default, Jun 2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> words = ['foo', 'bar']
>>> sentence = 'Some sentence bar the beach'
>>> match = any(x in sentence for x in words)
>>> match
True
但是在pdb中没有:
(Pdb) words = ['foo', 'bar']
(Pdb) words
['foo', 'bar']
(Pdb) sentence = 'Some sentence bar the beach'
(Pdb) sentence
'Some sentence bar the beach'
(Pdb) match = any(x in sentence for x in words)
*** NameError: name 'sentence' is not defined
(Pdb)
好的,我看到代码正在工作,但不是在pdb
中,pdb
的问题是什么?
这将为您提供所有匹配单词的列表
match = [x for x in words if x in sentence]