开发者

alphabetically sorted if statement not working

The if statement below has a problem in it somewhere and I can not figure it out. Any conven开发者_C百科tions or method misuses that might be causing it to not function right? checkList is a user inputed sentence and lis is a large list of words.

def realCheck(checkList):  
        string = "".join(checkList)  
    print string  
    wordList = string.split()  
    if match(wordList, lis).sort(key=str.lower) == wordList.sort(key=str.lower):  
        return True  
    else:  
        return False  


  1. If checkList is a string, then there is no need for "".join(checkList). It just gives you back the same string:

    In [94]: checkList="This is a sentence"    
    In [95]: "".join(checkList)
    Out[95]: 'This is a sentence'
    
  2. The first line, string = "".join(checkList) has the wrong indentation. Move it back to be flush with the other lines in the definition.

  3. Don't name a variable string. It overrides the standard Python module of the same name.

  4. Presumably match(wordList, lis) returns a list. The sort method sorts the list, and returns None. Since None == None is True,

    if match(wordList, lis).sort(key=str.lower) ==  wordList.sort(key=str.lower):
    

    is always true.

    More likely, what you want is

    sorted(astr.lower() for astr in match(wordList, lis))==sorted(astr.lower() for astr in wordList)
    

    Unlike the sort method, the sorted function returns the sorted list.

    As Alex Martelli points out,

    sorted(match(wordList, lis),key=str.lower)==sorted(wordList,key=str.lower)
    

    always has the same truth value as

    sorted(match(wordList, lis))==sorted(wordList)
    

    So using str.lower as the key for sorting (rather than as a transformation before comparing with ==) is probably not what you want.

  5. The statement

    if condition:
        return True
    else:
        return False
    

    can be simplified to

    return condition
    


.sort, like just about every other mutator method of containers, returns None. So comparing a.sort() to b.sort() is absurd because they'll both be None! I think you want to compare sorted(match(wordList, lis), key=str.lower) with sorted(worldList, key=str.lower).

Note that the key is actually irrelevant the way you're using it: if the two lists have items that differ in case, they will not compare equal even if they're sorted "comparably"!

So a better idea might be to compare sorted(s.lower() for s in match(wordList, lis)) with sorted(s.lower() for s in worList). Note that the key= is unneeded here since you're comparing the lowercased items so they'll sort that way "by nature".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜