Python 3.9中列表变元组引发AttributeError问题求助
问题排查与解决方案
核心原因
你遇到的矛盾现象(hasattr返回True但调用append报错),本质是**liste_poss变量在代码执行过程中被意外赋值成了元组**。元组是不可变类型,没有append方法,而你用hasattr验证的可能是变量初始化为列表时的状态,后续逻辑里它被改成了元组,导致报错。
具体排查点
- 检查
liste_poss的初始化:确保是用liste_poss = [](列表)而非liste_poss = ()(元组)初始化。 - 排查所有对
liste_poss的赋值操作:比如有没有写过liste_poss = some_tuple,或是在循环、函数返回时不小心把元组赋值给了它。 - 临时加调试代码:在报错行前插入
print(type(liste_poss)),直接打印当前变量类型,就能确认它是否为元组。
修复示例
以下是符合你需求的修正版代码参考,确保liste_poss全程保持列表类型:
texte = ["apple", "ant", "banana", "bear"] liste = [] seen_first_chars = set() for word in texte: if not word: continue first_char = word[0] if first_char not in seen_first_chars: seen_first_chars.add(first_char) liste_poss = [] # 明确初始化为列表 # 收集当前单词的后续字符 for j in range(len(word)): liste_poss.append(" " if j == len(word)-1 else word[j+1]) # 收集其他同首字母单词的后续字符 for other_word in texte: if other_word.startswith(first_char) and other_word != word: for k in range(len(other_word)): liste_poss.append(" " if k == len(other_word)-1 else other_word[k+1]) liste.append( (first_char, liste_poss) ) print(liste)
补充说明
你用liste_poss += (texte[i][j+1])报错,是因为(texte[i][j+1])不是元组(单个元素加括号仍为原类型),正确写法应为liste_poss += (texte[i][j+1],),但显然用列表的append方法更直观。
内容的提问来源于stack exchange,提问作者luna
相关产品推荐
相关产品推荐

