python错误:“索引错误:字符串索引超出范围”

2024-03-28 23:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题。当我试图从数组中查找progId元素中的索引时,出现了一个错误。你知道吗

当我尝试这个:

for index in range(0, self.channel_count):
    test = progId[index]
    test_index = index
    print test

错误在这条线上跳跃:

test = progId[index]

错误为:indexer错误:字符串索引超出范围

以下是完整代码:

self.channel_count = 0

if start_time < current_time < stop_time:
    print "program is half way"
    progId = list()

    for index in range(0, self.channel_count):
        test = progId[index]
        test_index = index
        print test_index
self.channel_count += 1

以下是self.channel_count中的值列表

19:13:23 T:6056  NOTICE: 0
19:13:23 T:6056  NOTICE: 1
19:13:23 T:6056  NOTICE: 2
19:13:23 T:6056  NOTICE: 3
19:13:23 T:6056  NOTICE: 4
19:13:23 T:6056  NOTICE: 5
19:13:23 T:6056  NOTICE: 6

以下是progId列表中的元素列表:

19:16:40 T:2112  NOTICE: 3003
19:16:40 T:2112  NOTICE: 3131
19:16:40 T:2112  NOTICE: 3259
19:16:40 T:2112  NOTICE: 3387
19:16:40 T:2112  NOTICE: 3515
19:16:40 T:2112  NOTICE: 3643
19:16:40 T:2112  NOTICE: 3771

你能告诉我怎么改正这个错误吗?你知道吗

编辑:当我尝试此操作时:

program_index = str(self.program_index)

for index in program_index:
    print index

我通过使用program_index得到这个值:

19:51:01 T:2888  NOTICE: 1
19:51:01 T:2888  NOTICE: 2
19:51:01 T:2888  NOTICE: 3
19:51:01 T:2888  NOTICE: 4

以下是progId列表中的元素列表:

19:16:40 T:2112  NOTICE: 3003
19:16:40 T:2112  NOTICE: 3131
19:16:40 T:2112  NOTICE: 3259
19:16:40 T:2112  NOTICE: 3387
19:16:40 T:2112  NOTICE: 3515
19:16:40 T:2112  NOTICE: 3643
19:16:40 T:2112  NOTICE: 3771

我想得到这样的结果:

19:16:40 T:2112  NOTICE: 3131
19:16:40 T:2112  NOTICE: 3259
19:16:40 T:2112  NOTICE: 3387
19:16:40 T:2112  NOTICE: 3515

那么如何使用索引从数组中找到元素呢?你知道吗


Tags: intestself元素列表forindextime
2条回答

在for循环的第一次运行中,self.channel_count是0。因此,range(0, self.channel_count)将是一个空列表,您将得到“索引超出范围”。你知道吗

range(0, self.channel_count)改成range(len(progId))。不清楚变量self.channel_countprogId包含什么。你知道吗

相关问题 更多 >