根据列表检查变量,并查看该列表中的单词是否以变量开头

时间:2016-10-06 02:34:05

标签: python

我正在尝试编写一个使用可以是任意长度的检查器的函数,并根据列表进行检查。检查和打印单词时应该不区分大小写。以下示例

Input= startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])

输出:

apple
ApPle 
Apple 
apricot

但是,它以小写形式打印列表中的每个字符串。

def startsWith(checker,lister):

    checker.lower()
    size = len(lister)
    i=0
    checklength = len(checker)
    lister = [element.lower() for element in lister]
    while(i<size):
        checkinlist = lister[i]
        if(checkinlist[0:checklength-1] in checker):
            # this is just to test to see if the variables are what i need
            # once the if statement works just append them to a new list
            # and print that
            print(lister[i])

        i=i+1

3 个答案:

答案 0 :(得分:1)

这是问题的根源

lister = [element.lower() for element in lister]

lister现在只包含小写字符串,然后打印。您需要延迟lower(),直到您检查checker为止。

无需检查任何长度。您可以使用filter

def startsWith(checker, lister):
    return list(filter(lambda x: x.lower().startswith(checker.lower()), lister))

for x in startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot']):
    print(x)

输出

apple
ApPle
Apple
apricot

答案 1 :(得分:0)

def startsWith(checker,lister):

    for i in range(len(lister)):
        words = lister[i].lower()
        if(words.startswith(checker)):
            print(lister[i])

def main():
    startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])
main()

输出

apple
ApPle
Apple
apricot
>>> 

答案 2 :(得分:0)

您不应该改变lister的原始元素,而是对已转换为小写的元素的新副本进行比较。

可以在单个列表理解中完成。

def startsWith(checker, lister):
    cl = checker.lower()
    return [s for s in lister if s.lower().startswith(cl)]

Input= startsWith('a',['apple','ApPle','orange','Apple','kiwi','apricot'])

for i in Input:
    print(i)

输出:

apple
ApPle
Apple
apricot