【问题标题】:incorrect return output in def()def() 中的错误返回输出
【发布时间】:2020-06-08 17:37:22
【问题描述】:

我应该:

“编写一个函数search(words, start_chs),它返回列表中所有单词的列表,其首字母在列表start_chs中。

如果单词或start_chs 为空,则返回一个空列表。

由于返回的列表中可以有很多单词,所以单词应该按照它们最初出现的顺序排列。”

例如

words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
start_chs = ['a', 'c', 'g']

new_words = search(words, start_chs)    # ['green', 'grasses', 'cats']

到目前为止,我的代码如下,但是,它没有返回所有正确的输出,只返回其中的一些。

def search(words, start_chs):
    k=0
    p=[]

    if (len(words)== 0) or (len(start_chs)== 0):
        return ([])
    while k < len(start_chs):
        if start_chs[k][0] == words[k][0]:
            p.append(words[k])
        k+=1
    return(p)

【问题讨论】:

  • 看起来您每个字母只检查一个单词。
  • 您对起始字符和单词使用相同的索引k。这意味着您将第一个起始字符 a 仅与第一个单词 green 进行比较,c 仅与 grasses 进行比较,g 仅与 frolicking 进行比较。
  • 你需要分别遍历wordsstart_chs。目前,k 用于两者。请注意,您可以使用 for 循环进行迭代,例如for word in words: for ch in starts_chs:.

标签: python python-3.x function while-loop


【解决方案1】:

你可以试试这个:-

def search(words, start_chs):
    res = []
    for word in words:
        if word!='' and word[0] in start_chs:
            res.append(word)
    return res

search(words, start_chs)

输出:

['green', 'grasses', 'cats']

【讨论】:

    【解决方案2】:

    应该是这样的。使用带有索引的迭代列表是不好的做法,请改用for element in list。 关于您的代码,为什么它不起作用。这是因为您应该遍历整个列表。在此示例中,您仅检查 'a' 是否等于 'green' 中的第一个字母、'grasses' 中的 'c''frolicking' 中的 'g'

    words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
    start_chs = ['a', 'c', 'g']
    
    def search(words, start_chs):
        result = []
    
        if len(words)== 0 or len(start_chs)== 0:
            return []
        for word in words:
            if word and word[0] in start_chs:
                result.append(word)
        return result
    
    print(search(words, start_chs))
    

    【讨论】:

      【解决方案3】:

      您编写的代码的问题是您只检查单词相应索引处的字符。所以你可以使用in 来代替它。

      def search(words, start_chs): 
         k=0 
         p=[] 
         if (len(words)== 0) or (len(start_chs)== 0): 
             return [] 
         for i in words: 
             if  i[0] in start_chs: 
                 p.append(i) 
             k+=1 
         return p 
      

      【讨论】:

        【解决方案4】:

        试试这个:

        def search(words, start_chs):
            start_chs = tuple(start_chs)
            return [word for word in words if word.startswith(start_chs)]
        
        words = ['green', 'grasses', 'frolicking', 'cats', '', 'kittens', 'playful']
        start_chs = ['a', 'c', 'g']
        
        new_words = search(words, start_chs)
        #['green', 'grasses', 'cats']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-20
          • 2013-07-23
          • 1970-01-01
          • 2022-10-23
          • 2017-11-30
          • 2021-09-03
          • 2016-08-24
          • 1970-01-01
          相关资源
          最近更新 更多