当前位置:  开发笔记 > 编程语言 > 正文

如何检查列表中是否存在字符串

如何解决《如何检查列表中是否存在字符串》经验,为你挑选了1个好方法。

我的代码的重点是检查4个单词的句子以及它是否长4个单词.

import random
import time
import urllib

numwords = 4
#getWordList
wordlist = []
def getWordList() :

    url = "some word list url"
    flink = urllib.urlopen(url)
    #print "Reading words from %s" % url
    words = [ ]            # word list
    for eachline in flink :
        text = eachline.strip()
        text = text.replace('%','')
        words += [text.lower()]
    flink.close()
    #print "%d words read" % len(words)
    words.append('i','am','an','to')
    return wordlist


warning = "\n"
prompt = "Enter a sentence with four words: "
while warning:
    usrin = raw_input(warning + prompt)
    usrwords = usrin.strip().lower().split() # a list
    print "The sentence is:", ' '.join(usrwords)
    warning = ''
    if len(usrwords) != numwords: #check length
        warning += ("\n%d words sought; %d obtained \n") %(numwords, len(usrwords))
    invalid = []
    for word in usrwords:
        if word not in wordlist :
            if word not in invalid:
                invalid.append(word)
    if invalid:
        warning += ("\ninvalid words found: %s\n") %(','.join(invalid))

由于某些原因,它没有正确地检查我的单词,并且它指出我输入的每个单词都是无效的.我也想知道我"I am an to"是否正确地附加到列表中.
提前致谢.



1> Hyperboreus..:

回答你原来的问题:

如何检查列表中是否存在字符串

in运营商:

>>> a = ['i', 'am', 'here', 42, None, ..., 0.]
>>> 'i' in a
True
>>> 'you' in a
False
>>> 'a' in a
False

读一下你的代码,似乎你想要识别一个列表中的所有单词,而不是另一个单词中的单词("无效单词").

invalid = {word for word in userWords if word not in validWords}

例:

>>> validWords = ['I', 'am']
>>> userWords = ['I', 'well', 'am', 'well']
>>> {word for word in userWords if word not in validWords}
{'well'}

我也想知道我是否正确地将"我是一个人"添加到列表中.

无需怀疑.当您收到错误时,通常无法正常执行此操作:

TypeError: append() takes exactly one argument (4 given)

编辑

我可以自由地改变你的一些代码:

#! /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

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有