python - Python 中的列表迭代

标签 python list for-loop

所以我得到这个错误:

TypeError: list indices must be integers, not str

指向这行代码:

if snarePattern[i] == '*':

每当我使用我认为简单的 Python 时

snarePattern = ['-', '*', '-', '*']
for i in snarePattern:
    if snarePattern[i] == '*':
        ...

这是不允许的吗?我不知道什么?

另外,如果有人知道我要处理这段代码,你能想出一种更简单的方法来创建和解析像这样的简单模式吗???我是 Python 新手。

谢谢大家

最佳答案

for i in snarePattern: 遍历每个 item 而不是每个索引:

>>> snarePattern = ['-', '*', '-', '*']
>>> for c in snarePattern:
        print c


-
*
-
*

可以改成

for i in range(len(snarePattern)):

如果你真的需要它,但看起来你不需要,例如检查是否 c == '*'

更好的遍历索引的方法是

for i, c in enumerate(snarePattern):  # i is each index, c is each character

关于python - Python 中的列表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137837/

相关文章:

python - Scrapy 中分页出现 KeyError

python - Python中的吉他弦代码?

Python:列表数组中的唯一值

javascript - For 循环变量索引

python - 使用列表中的项目创建文件名 - for 循环

python - 消息类型 websocket gdax (coinbase)

python - 在 OSX 上使用可信连接通过 Pyodbc 连接到 SQLServer

list - 如何展平斯卡拉的 future list

c++ - 洗牌 QStringList 中的元素

swift - 在 Xcode 的 UILabel 上显示 Double 类型的数组