按字母顺序排序if语句不起作用

时间:2010-10-02 23:34:16

标签: python mutators

下面的if语句在某个地方有问题,我无法弄清楚。任何可能导致其无法正常运行的约定或方法滥用? checkList是用户输入的句子,lis是一个很大的单词列表。

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  

2 个答案:

答案 0 :(得分:5)

  1. 如果checkList是一个字符串,那么那里 不需要"".join(checkList)。 它只是让你回来 字符串:

    In [94]: checkList="This is a sentence"    
    In [95]: "".join(checkList)
    Out[95]: 'This is a sentence'
    
  2. 第一行string = "".join(checkList)有错误 缩进。把它移回去 与其他线齐平 定义

  3. 不要为变量string命名。它 覆盖标准的Python模块 同名。

  4. 据推测match(wordList, lis) 返回一个列表。排序方法 对列表进行排序,然后返回None。 由于None == NoneTrue

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

    总是如此。

    更有可能,你想要的是

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

    sort方法不同, sorted函数返回 排序清单。

    正如Alex Martelli指出的那样,

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

    始终具有与

    相同的真值
    sorted(match(wordList, lis))==sorted(wordList)
    

    因此使用str.lower作为key 用于排序(而不是作为 比较之前的转变 ==)可能不是你想要的。

  5. 声明

    if condition:
        return True
    else:
        return False
    

    可以简化为

    return condition
    

答案 1 :(得分:4)

.sort,就像其他容器的mutator方法一样,返回None。因此,将a.sort()b.sort()进行比较是荒谬的,因为它们都是None!我想您要将sorted(match(wordList, lis), key=str.lower)sorted(worldList, key=str.lower)进行比较。

请注意,key实际上与您使用它的方式无关:如果两个列表的项目大小不同,即使它们是 比较相等排序“可比”!

因此,更好的想法可能是将sorted(s.lower() for s in match(wordList, lis))sorted(s.lower() for s in worList)进行比较。请注意,此处不需要key=,因为您要比较小写项目,以便他们按照“自然”排序。