Python数组元素匹配计数程序输出错误排查求助
数组元素出现次数统计程序输出错误的解决方法
我正在编写一个Python程序,用于统计第二个数组的每个元素在第一个数组中的出现次数,并将统计结果存入整数列表。示例输入(原垂直输入改为水平展示便于理解)如下:
Number of elements of the first array : 4
Number of elements of the second array : 3
elements of the first array : aba baba aba xzxb
elements of the second array : aba xzxb ab
预期输出为2 1 0,但当前程序输出结果为2 0 0,调试后未找到问题原因。
以下是我的代码:
nElemL1 = int(input("Insert the number of elements of the first array\n")) nElemL2 = int(input("Insert the number of elements of the second array\n")) list1 =[] list2 = [] print("Insert the elements of the first array\n") for i in range (nElemL1) : someElement = input() list1.append(someElement) print("Insert the elements of the second array\n") for i in range (nElemL2) : someElement = input() list2.append(someElement) listCounts =[] for j in range (nElemL2) : counti = 0 for i in range (nElemL1) : if i == (nElemL1-1) : if list2[j] == list1[i] : counti = counti+1 listCounts.append(counti) elif list2[j] == list1[i] : counti = counti+1 print ("\n\nAnswers\n\n") for i in listCounts : print (i)
备注:
- 示例中的输入原本是垂直输入(如同普通Python终端程序),我改为水平输入以便于理解。
- 该Python程序是为验证C版本代码逻辑而编写的Demo,请不要使用C中
<algorithm>和<string>库等效的Python函数(如find或count),因为我目前对这些函数还不太理解。
问题分析
你的代码核心逻辑错误出在统计结果的时机上:你仅在内层循环遍历到第一个数组的最后一个元素时,才将统计次数加入结果列表。这种写法把统计逻辑和循环边界判断耦合在一起,不仅没必要,还极易因输入细节(比如元素首尾空格)或边界判断失误导致错误。
比如示例中xzxb的统计,若输入时第一个数组的最后一个元素带了多余空格,就会和第二个数组的xzxb匹配失败,导致统计次数为0,和预期结果不符。
修正后的代码
nElemL1 = int(input("Insert the number of elements of the first array\n")) nElemL2 = int(input("Insert the number of elements of the second array\n")) list1 = [] list2 = [] print("Insert the elements of the first array\n") for i in range(nElemL1): someElement = input().strip() # 去除输入首尾空白字符,避免匹配误差 list1.append(someElement) print("Insert the elements of the second array\n") for i in range(nElemL2): someElement = input().strip() list2.append(someElement) listCounts = [] for j in range(nElemL2): counti = 0 for i in range(nElemL1): if list2[j] == list1[i]: counti += 1 # 遍历完第一个数组所有元素后,再存入统计结果 listCounts.append(counti) print("\n\nAnswers\n\n") # 按示例格式输出空格分隔的结果 print(' '.join(map(str, listCounts)))
关键修改点
- 调整结果存入时机:将
listCounts.append(counti)移到内层循环外,确保遍历完第一个数组所有元素后,再把最终统计次数加入结果列表,逻辑更清晰,避免边界判断失误。 - 添加输入清洗:用
strip()去除输入字符串首尾的空格、换行符,避免因输入误操作导致元素匹配失败。 - 优化输出格式:将结果列表转为空格分隔的字符串,和示例输出格式一致。
修改后的代码逻辑简洁,能避免输入细节导致的匹配错误,运行后即可得到预期的2 1 0输出。
内容的提问来源于stack exchange,提问作者HaveMercy
相关产品推荐
相关产品推荐

