You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中两个函数配合使用时+=统计列表目标值出现次数功能异常问题

问题根源
  • 错误出在count_target_in_list函数的遍历逻辑:你先通过用户输入把目标值存入target_val变量,后续遍历整数列表时又复用了target_val作为临时遍历变量,直接覆盖了原本的目标值。
  • 遍历过程中没有判断当前元素是否等于目标值,每次循环都直接执行count += 1,所以最终count值必然等于列表的总条目数。
修正后的完整代码
def get_int_list_from_user():
    list1 = []
    numNums = int(input("Enter number count: "))
    for x in range(numNums):
        nextval = int(input("Enter a whole number: "))
        list1.append(nextval)
    return list1

def count_target_in_list(int_list):
    target_val = int(input("Enter target value: "))
    count = 0
    # 替换遍历临时变量名,增加相等判断逻辑
    for item in int_list:
        if item == target_val:
            count += 1
    print("Target counted ", count, "time(s)")
    return count
调用说明

原有的两种调用方式无需修改即可正常运行:
第一种调用方式:

list1 = my_functions.get_int_list_from_user()
count = my_functions.count_target_in_list(int_list=list1)

第二种调用方式:

my_functions.count_target_in_list(int_list=my_functions.get_int_list_from_user())

内容的提问来源于stack exchange,提问作者Grelm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:45:01