<p>回答您最初的问题:</p>
<blockquote>
<p>How do I check if a string exists in a list</p>
</blockquote>
<p>使用<code>in</code>运算符:</p>
<pre><code>>>> a = ['i', 'am', 'here', 42, None, ..., 0.]
>>> 'i' in a
True
>>> 'you' in a
False
>>> 'a' in a
False
</code></pre>
<p>读一读你的代码,你似乎想找出一个列表中的所有单词,而另一个列表中没有这些单词(“无效单词”)。你知道吗</p>
<pre><code>invalid = {word for word in userWords if word not in validWords}
</code></pre>
<p>示例:</p>
<pre><code>>>> validWords = ['I', 'am']
>>> userWords = ['I', 'well', 'am', 'well']
>>> {word for word in userWords if word not in validWords}
{'well'}
</code></pre>
<hr/>
<blockquote>
<p>I was also wondering if I appended "I am an to" to the list properly.</p>
</blockquote>
<p>不用奇怪。当您遇到错误时,通常不会正确执行:</p>
<pre><code>TypeError: append() takes exactly one argument (4 given)
</code></pre>
<hr/>
<p><strong>编辑</p>
<p>我可以随意更改您的代码:</p>
<pre><code>#! /usr/bin/python2.7
NUMWORDS = 4
#you get your wordlist from somewhere else
wordlist = ['i', 'am', 'a', 'dog']
while True:
usrwords = raw_input("\nEnter a sentence with four words: ").strip().lower().split()
print "The sentence is: {}".format(' '.join(usrwords))
if len(usrwords) != NUMWORDS:
print "\n{} words sought; {} obtained \n".format(NUMWORDS, len(usrwords))
continue
invalid = {word for word in usrwords if word not in wordlist}
if invalid:
print "\ninvalid words found: {}\n".format(', '.join(invalid))
continue
print 'Congratulations. You have entered a valid sentence: {}'.format(' '.join(usrwords))
#do here whatever you must
</code></pre>