Python计算哈希方法标准差时,列表字符串索引0报错问题求助
问题解决:哈希函数计算标准差时的字符串索引错误
核心错误原因
- 文件读取逻辑错误:原代码中
for line in dictionary: dictlist.append(dictionary.readline())会导致每轮循环跳过一行文本,还可能读取到文件末尾的空字符串(""),空字符串无法通过[0]访问首字符,直接触发“无效字符串索引”错误。 - 哈希函数语法错误:
hash2和hash3函数里使用list2(...)、list3(...)的方式错误,应该调用append()方法向列表添加元素,否则哈希值不会被存入列表,后续计算方差会出错。
修复步骤
- 修正文件读取:直接将遍历到的
line去除首尾空白后加入列表,避免空字符串和跳行问题:with open("dict.txt","r") as dictionary: for line in dictionary: stripped_line = line.strip() if stripped_line: # 跳过空行 dictlist.append(stripped_line) - 修复哈希函数的添加逻辑:把
hash2和hash3里的list2(...)改为list2.append(...),list3(...)改为list3.append(...)。 - 优化方差计算(可选):可以用numpy内置的
np.std()替代自定义的variance函数,简化代码,结果一致。
修复后的完整代码
import numpy as np listhash1 = [] listhash2 = [] listhash3 = [] dictlist = [] def hash1(input_list, result_list): for s in input_list: result_list.append(ord(s[0].upper()) + len(s) - ord('A')) return result_list def hash2(input_list, result_list): for s in input_list: hash_val = ((ord(s[0].upper()) - ord('A')) * len(s)) % 100 result_list.append(hash_val) def hash3(input_list, result_list): for s in input_list: hash_val = ((ord(s[0].upper()) - ord('A')) % len(s)) result_list.append(hash_val) # 用numpy内置函数替代自定义方差计算,更简洁 def variance(input_list): return np.std(input_list) # 修正文件读取逻辑 with open("dict.txt","r") as dictionary: for line in dictionary: stripped_line = line.strip() if stripped_line: dictlist.append(stripped_line) # 分别传入空列表存储不同哈希结果,避免复用同一列表导致数据混乱 hash1(dictlist, listhash1) hash2(dictlist, listhash2) hash3(dictlist, listhash3) print(variance(listhash1), "\n", variance(listhash2), "\n", variance(listhash3), "\n")
运行结果
7.631627233244063 28.864721512130362 2.8228899955211144
内容的提问来源于stack exchange,提问作者Vrajesh Kumar
相关产品推荐
相关产品推荐

