簡體   English   中英

如何返回具有特定要求的字符串在列表中出現的次數?

[英]How to return the number of times a string with specific requirements appears in a list?

給定一個字符串列表,返回字符串長度為 3 或更多並且字符串的第一個和最后一個字符相同的字符串數量的計數。

為了解決這個問題,我創建了以下函數,

def match_ends(words):
  FirstL=words[0:1]
  LastL=words[-1:]
  x=len(words)>3 and FirstL == LastL
  count=0
 for x in words:
    count+=1
    return count

然后在這里測試,

def test(got, expected):
  if got == expected:
    prefix = ' OK '
  else:
    prefix = '  X '
  print ('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))


# Calls the above functions with interesting inputs.
def main():
  print ('match_ends')
  test(match_ends(['abaa', 'xyzax', 'aa', 'x', 'bbb']), 3)
  test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 1)
  test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)


  print

結果:

X  got: 1 expected: 3
OK  got: 1 expected: 1
OK  got: 1 expected: 1

你在這里有幾個問題:

  1. 當您循環遍歷每個單詞時,您return在循環內return count ,而不是在循環結束時return count 這就是為什么你總是得到1

  2. 即使xFalse你也總是count += 1

  3. x取列表的第一個和最后一個項目,而不是列表中每個單詞的第一個和最后一個字母。

  4. 最后,在for循環中bool x


提示

為什么不把它分成兩個功能呢?

 def match_end(word): first, last = word[0], word[-1:] return True if first == last and len(word) >= 3 else False def match_ends(words): count = 0 for word in words: count += 1 if match_end(word) else 0 return count

第一個函數match_end(word)返回一個bool TrueFalse

  • 首先,它通過切片將變量firstlast設置為字符串的第一個和最后一個字母。

  • 接下來,如果第一個字母與最后一個字母相同,並且單詞的長度小於三個,則return s True 否則,它return s False 這是通過 Python 的Ternary Operator 完成的

第二個函數match_ends(words)接受一個字符串列表(就像你原來的那樣)遍歷list每個單詞。

  • 對於列表中的每個單詞,它會測試match_end(word)返回True

    • 如果是,它將計數增加1

    • 否則,它什么都不做(將 count 增加0 )。

  • 最后,它返回count

最好的辦法是使用列表理解。 列表理解包含三個部分:

  • 您要對輸入的每個元素執行的轉換,
  • 輸入本身,以及
  • 一個可選的“if”語句,指示何時產生輸出

例如,我們可以說

[ x * x               # square the number
for x in range(5) ]  # for each number in [0,1,2,3,4]  `

這將產生列表

[0 1 4 9 16]

我們可以添加第三行(過濾),然后只返回奇數:

[x * x
for x in range(5) 
if x % 2]     # divide x by 2, take the remainder -- if 1, output the number`

在您的特定情況下,我們不關心轉換部分。 我們只想輸出符合您標准的單詞:

[word
 for word in word_list
 if len(word) >= 3 and word[0] == word[-1] ]

這會給你一個列表。 現在您只需要獲取該列表的長度:

len( [word
 for word in word_list
 if len(word) >= 3 and word[0] == word[-1] ]  )

想把它變成一個函數嗎? 干得好:

def count_matching_words(word_list):
    return len([word
                for word in word_list
                if len(word) >= 3 and word[0] == word[-1]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM