我正在尝试编写一个函数,该函数使用可以是任何长度的检查器,并根据列表进行检查。检查和打印单词时应不区分大小写。下的示例
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
以下是问题的根源
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
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
>>>
您不应该更改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