gpt4 book ai didi

Python - 在 For 循环中列出超出范围的索引

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:24 25 4
gpt4 key购买 nike

我是 python 的新手,目前正在开发一个加密和解密字符串的程序。作为其中的一部分,我需要将字符串的各个字母分别添加到一个空列表中;例如,字符串 'hello' 将被输入到列表列表中,如下所示:

['h','e','l','l','o']

给我这个错误的代码部分可以在下面找到。谢谢。

emptyList=[]
message=input("What Would You Like To Encrypt?\n")

messageLength=len(message)
for count in range(0,messageLength):
emptyList=[]
emptyList[count].append(message[count])

最佳答案

您正在尝试处理空列表中的索引:

>>> lst = []
>>> lst[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

如果您想向列表添加元素,只需在列表对象本身上直接使用list.append() 来创建更多索引;不要每次都创建新的空列表:

emptyList=[]
messageLength=len(message)
for count in range(0,messageLength):
emptyList.append(message[count])

不需要这么详细,以下就足够了:

emptyList = list(message)

list() 获取任何可迭代对象并将该可迭代对象的所有元素添加到列表中。由于字符串是可迭代的,会生成该字符串中的所有字符,因此对字符串调用 list() 会创建这些字符的列表:

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

关于Python - 在 For 循环中列出超出范围的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com