Message=list indices must be integers or slices, not itertools.permutations Source=E:\1daer\mmxdzy\1\dzy1\dzy1.py StackTrace: File "E:\1daer\mmxdzy\1\dzy1\dzy1.py", line 45, in guess_key1 key.update({most_common_letters_m[i][mp[j]]: mf[i][j]}) ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^ File "E:\1daer\mmxdzy\1\dzy1\dzy1.py", line 72, in <module> (Current frame) print(guess_key1(cipher_text, words)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: list indices must be integers or slices, not itertools.permutations
时间: 2023-09-30 10:07:43 浏览: 83
这个错误提示是因为在代码中使用了 `mp[j]` 作为列表的索引,而 `mp[j]` 是一个 `itertools.permutations` 对象,不能作为列表的索引。需要将 `mp` 中的元素改为整数类型的索引,才能正确地访问到列表中的元素。可以使用 `list` 函数将 `itertools.permutations` 对象转换为列表,或者使用 `next` 函数获取 `itertools.permutations` 对象中的下一个元素。
相关问题
TypeError: list indices must be integers or slices, not str.
### 解决 Python 中 `TypeError: list indices must be integers or slices, not str` 错误的方法
当尝试使用字符串作为索引来访问列表中的元素时,会出现此错误。Python 列表仅接受整数或切片对象作为索引[^1]。
#### 原因分析
该错误通常发生在代码试图像字典那样对待列表,即用字符串键来获取值。然而,在 Python 中,列表是通过位置(整数索引)而不是键名来访问其成员的。
#### 修正方法一:确认数据结构类型
如果意图是对列表操作,则应确保确实是在处理一个列表而非其他类型的序列或映射对象;如果是想要查找特定项的位置可以考虑遍历整个数组找到目标元素或者转换成适合按关键字查询的数据结构比如字典。
```python
# 不正确的做法
my_list = ['apple', 'banana']
print(my_list['0']) # 这会引发 TypeError
# 正确的做法
index = int('0') # 将字符串形式的索引转为整型
print(my_list[index]) # 输出第一个元素 apple
```
#### 修正方法二:更改数据结构至字典
假如实际需求是要依据名称取回对应的数值,那么应该创建的是字典而不是列表:
```python
# 使用字典代替列表以便于按照 key 获取 value
fruit_dict = {'first': 'apple', 'second': 'banana'}
print(fruit_dict['first'])
```
以上两种方式都可以有效避免由于误解而产生的上述异常情况。选择哪种取决于具体应用场景以及个人偏好。
list indices must be integers or slices, not lxml.etree._ElementUnicodeResult
这个错误提示通常出现在使用lxml库中的xpath查询时,当你使用xpath查询后,返回结果是一个unicode字符串而不是一个列表或切片时,就会出现这个错误。
解决方法:
1. 确保使用xpath查询后,返回的是一个列表或者切片
2. 如果返回的是一个unicode字符串,需要使用来获取第一个元素
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)