Python程序:搜索列表中特定数字出现的次数
当需要搜索列表中数字的出现频率时,定义一个方法,该方法接受一个列表和一个数字作为参数。它迭代列表,每次遇到该数字时,计数器就会递增。
以下是相同的演示:
示例
def count_num(my_list, x_val): my_counter = 0 for elem in my_list: if (elem == x_val): my_counter = my_counter + 1 return my_counter my_list = [ 66, 26, 48, 140, 66, 20, 1, 96, 86] print("The list is :") print(my_list) occ_number = 66 print('{} has occurred {} times'.format(occ_number, count_num(my_list, occ_number)))
输出
The list is : [66, 26, 48, 140, 66, 20, 1, 96, 86] 66 has occurred 2 times
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
定义了一个名为“count_number”的方法,它接受一个列表和一个数字作为参数。
迭代列表,如果任何元素与数字匹配,则递增计数器。
计数器作为函数的结果返回。
在函数外部,定义一个列表,并在控制台上显示。
定义数字,并通过传递这些参数来调用该方法。
输出显示在控制台上。
广告