简体   繁体   English

TypeError:'int'对象在python3.8中不可下标

[英]TypeError: 'int' object is not subscriptable in python3.8

Alphabet = ["a","b","c","ç","d","e","f","g","ğ","h","ı","i","j","k","l","m","n","o","ö","p","r","s","ş","t","u","ü","v","y","z"]

message = 'cöimamiçknsyznhaczstş'
for i in range(len(message)):
    message = Alphabet.index(message[i])

I m trying to write simple code but I keep getting this TypeError: 'int' object is not subscriptable error我正在尝试编写简单的代码,但我不断收到此TypeError: 'int' object is not subscriptable错误

I just want to get index of each char of message我只想获取消息每个字符的索引

You are doing everything correctly, just a little change is needed because in your code you are overwriting our message variable.你做的一切都是正确的,只需要一点点改变,因为在你的代码中你覆盖了我们的message变量。 here is how you can fix it这是您可以修复它的方法

 Alphabet = ["a","b","c","ç","d","e","f","g","ğ","h","ı","i","j","k","l","m","n","o","ö","p","r","s","ş","t","u","ü","v","y","z"] message = 'cöimamiçknsyznhaczstş' char_indexes = [] for i in range(len(message)): char_indexes.append(Alphabet.index(message[i])) print(char_indexes)

Another method to do the same is to useList comprehension as follows.另一种方法是使用List comprehension ,如下所示。

 Alphabet = ["a","b","c","ç","d","e","f","g","ğ","h","ı","i","j","k","l","m","n","o","ö","p","r","s","ş","t","u","ü","v","y","z"] message = 'cöimamiçknsyznhaczstş' char_indexes = [Alphabet.index(message[i]) for i in range(len(message))] print(char_indexes)

You are overwriting message and it becomes integer after first iteration.您正在覆盖message并在第一次迭代后变为整数。 Try this:尝试这个:

Alphabet = ["a","b","c","ç","d","e","f","g","ğ","h","ı","i","j","k","l","m","n","o","ö","p","r","s","ş","t","u","ü","v","y","z"]

placeholder_list = []
message = "cöimamiçknsyznhaczstş"
for i in range(len(message)):
    placeholder_list.append(Alphabet.index(message[i]))
print(placeholder_list)

After the first iteration, you assign to message the index of the first location of the first letter of the original message which is 2. In the next iteration, message=2 and you try to do message[1] but message is not an integer and therefore it is not subscriptable.在第一次迭代后,您将原始message的第一个字母的第一个位置的索引分配给message ,即 2。在下一次迭代中, message=2并且您尝试执行message[1]message不是整数因此它是不可下标的。

The solution is probably to change the loop to something like -解决方案可能是将循环更改为类似 -

for i in range(len(message)):
    x = Alphabet.index(message[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM