![](/img/trans.png)
[英]How to access the next item of a list, inside the (for item in list) loop ? (Python 3)
[英]Python how to access list item with a variable
今晚我搜索了一段时间,但没有找到任何东西......或者我太菜鸟无法理解? 好吧,这是我的代码,问题随之而来,我想如果我现在向您展示代码,您会更好地理解它:
lencount = 1
decrypted = []
while lencount <= length:
if intlist[lencount] == 2:
print('OK!')
decrypted.append(alphabet[2])
lencount += 1
print(decrypted)
这是整个代码,如果你想看:
import os
# os.system("multimon-ng -a dtmf -q | grep -x -E '[0-9]+' --line-buffered >> $HOME/dtmf.txt")
file=open('/home/nicolasmailloux/dtmf.txt')
line=file.read()
text = line.replace("\n", "")
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
ngram = "".join(chars[i:i+n])
ngrams.append(ngram)
intlist = list(map(int, ngrams))
length = int(len(intlist))
print(length)
print(intlist)
# Defining some variables
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
lencount = 1
decrypted = []
while lencount <= length:
if intlist[lencount] == 2:
print('OK!')
decrypted.append(alphabet[2])
lencount += 1
print(decrypted)
问题是列表中的项目数量是可变的,我无法通过使用intlist[lencount]
的变量访问它(为什么??)。 这令人困惑。 这是我尝试运行程序时的输出:
if intlist[lencount] == 2:
IndexError: list index out of range
感谢您的帮助!
这是因为len()
函数返回:
对象的长度(项目数)。
但是,列表在 Python 中是零索引的,这意味着some_list[len(some_list)]
将始终超出范围,因为len()
不考虑零索引。
因此,条件while lencount <= length
允许intlist[len(intlist)]
发生,根据定义,这超出了范围。 这可以通过以下方式解决:
while lencount < length:
if intlist[lencount] == 2:
print('OK!')
...
此外,假设您要查看intlist
所有值,则lencount
应初始化为 0,因此:
lencount = 0
这是问题所在:
length = int(len(intlist))
结合
while lencount <= length:
if intlist[lencount] == 2:
lencount=length
超出范围(索引从0, ..., len(list)-1
)。
镜头数 = 1
问题是您的 lencount 以 1 开头
你的while循环是这样的,
lencount = 30 如果 intlist[31] == 2:
但是 inlist len 是 30,
您正在尝试查找索引 31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.