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

标签 python string list

我是 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/

相关文章:

python - 如何在窗口内对齐 QPushButton?

c - 函数中的操作数组 - c - 段错误

python - 如何按字典中的值对字典列表进行排序?

c - 传递给嵌套函数的字符串文字指针问题

c++ - 找出字符串是否仅包含给定字符集的最佳方法/算法

python - 如何从 python 中的列表中获取第一个值和最后一个值?

在现有 LinkedList<T> 中添加新项的 C# 最佳方法?

python - Django 'if and' 模板

python - 我可以仅使用诗歌安装新版本的 python 吗?

python - 使用 virtualenvwrapper 重命名环境