在 Python 列表中统计出现次数

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,经常需要统计列表中特定值出现的次数。这在各种情况下都很有用,例如分析数据或处理用户输入。在这个挑战中,你将负责编写一个函数,用于统计列表中给定值出现的次数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") subgraph Lab Skills python/comments -.-> lab-13609{{"在 Python 列表中统计出现次数"}} python/lists -.-> lab-13609{{"在 Python 列表中统计出现次数"}} python/tuples -.-> lab-13609{{"在 Python 列表中统计出现次数"}} python/function_definition -.-> lab-13609{{"在 Python 列表中统计出现次数"}} end

统计出现次数

编写一个函数 count_occurrences(lst, val),它接受一个列表 lst 和一个值 val 作为参数,并返回 vallst 中出现的次数。你的函数应该使用内置的 list.count() 方法来统计出现次数。

def count_occurrences(lst, val):
  return lst.count(val)
count_occurrences([1, 1, 2, 1, 2, 3], 1) ## 3

总结

在这个挑战中,你学习了如何使用 list.count() 方法来统计列表中某个值出现的次数。这是一项在各种编程任务中都能应用的实用技术。