简体   繁体   English

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

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

Given a list of strings, return the count of the number of strings where the string length is 3 or more and the first and last chars of the string are the same.给定一个字符串列表,返回字符串长度为 3 或更多并且字符串的第一个和最后一个字符相同的字符串数量的计数。

To solve this problem I created the following function,为了解决这个问题,我创建了以下函数,

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

then tested it here,然后在这里测试,

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

Result:结果:

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

You have a few problems here:你在这里有几个问题:

  1. When you're looping over each of the words, you return count within the loop, instead of at the end when the loop finishes.当您循环遍历每个单词时,您return在循环内return count ,而不是在循环结束时return count This is why you were always getting 1 .这就是为什么你总是得到1

  2. You always count += 1 even if x is False .即使xFalse你也总是count += 1

  3. x is taking the first and last item of the list, rather than the first and last letter in each word in the list. x取列表的第一个和最后一个项目,而不是列表中每个单词的第一个和最后一个字母。

  4. Finally you shadow the bool x in your for loop.最后,在for循环中bool x


Tips 提示

Why not split this into two functions?为什么不把它分成两个功能呢?

 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

The first function, match_end(word) returns a bool of either True or False .第一个函数match_end(word)返回一个bool TrueFalse

  • First, It sets the variables first and last to the first and last letter of the string via slicing.首先,它通过切片将变量firstlast设置为字符串的第一个和最后一个字母。

  • Next, it return s True if the first letter is the same as the last, and if the length of the word is less than three.接下来,如果第一个字母与最后一个字母相同,并且单词的长度小于三个,则return s True Otherwise, it return s False .否则,它return s False This is done with Python's Ternary Operator .这是通过 Python 的Ternary Operator 完成的

The second function, match_ends(words) , takes in a list of strings(like your original one) iterates over each word in the list .第二个函数match_ends(words)接受一个字符串列表(就像你原来的那样)遍历list每个单词。

  • For each word in the list, it tests to see if match_end(word) returns True .对于列表中的每个单词,它会测试match_end(word)返回True

    • If so, it increments the count by 1 .如果是,它将计数增加1

    • Otherwise, it does nothing (increments count by 0 ).否则,它什么都不做(将 count 增加0 )。

  • Finally, it returns count .最后,它返回count

Your best bet here is to use a list comprehension.最好的办法是使用列表理解。 A list comprehension has three parts:列表理解包含三个部分:

  • The transformation that you want to perform on each element of the input,您要对输入的每个元素执行的转换,
  • the input itself, and输入本身,以及
  • an optional "if" statement that indicates when to produce output一个可选的“if”语句,指示何时产生输出

So for example, we can say例如,我们可以说

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

which will produce the list这将产生列表

[0 1 4 9 16]

We can add a third (filtering) line, and get only odd numbers back:我们可以添加第三行(过滤),然后只返回奇数:

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

In your particular case, we don't care about the transformation part.在您的特定情况下,我们不关心转换部分。 We just want to output the word if it fits your criteria:我们只想输出符合您标准的单词:

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

This will give you a list back.这会给你一个列表。 Now you just need to get the length of that list:现在您只需要获取该列表的长度:

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

Want to turn that into a function?想把它变成一个函数吗? Here you go:干得好:

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.

相关问题 如何计算特定字符在列表中出现的次数? - How to count the number of times a specific character appears in a list? 使用循环返回字符串出现的次数 - Return the number of times that the string appears using loops 计算字符串在特定列中出现的次数 - Count the number of times a string appears in a specific column 计算字符串在列表中出现的次数 - Count the number of times a string appears in a list 如何使用while循环计算特定数字出现在列表中的次数? - How to use a while loop to count the number of times a specific number appears in a list? 返回字符串“code”出现在给定字符串中任意位置的次数 - Return the number of times that the string "code" appears anywhere in the given string 尝试查找项目出现在另一个字符串列表中的次数 - Try to find the number of times an item appears in another list of list of string 如何让我的 output 返回 '*' 每个字母在字符串中出现的次数? - How can I make my output return '*' for the number of times each letter appears in a string? 如何返回包含短语的元组列表,以及它按降序出现的次数? - How do I return a list of tuples containing a phrase, and the number of times it appears in descending order? Python:如何使用显示特定次数的python列表中的项目? - Python: How to use an item from a python list which appears a specific number of times?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM