Python 索引器:列表索引超出范围-有时运行,有时不运行
我有一种情况,我不知道如何解决。 有时当我运行程序时,它运行得非常完美,有时它会说Python 索引器:列表索引超出范围-有时运行,有时不运行,python,python-3.x,Python,Python 3.x,我有一种情况,我不知道如何解决。 有时当我运行程序时,它运行得非常完美,有时它会说 list index out of range 守则: hashtag_list = ['urban', 'hipster', 'retro'] for hashtag in hashtag_list: tag = randint(1,3) driver.get('https://www.instagram.com/explore/tags/' + hashtag_list[tag] + '/'
list index out of range
守则:
hashtag_list = ['urban', 'hipster', 'retro']
for hashtag in hashtag_list:
tag = randint(1,3)
driver.get('https://www.instagram.com/explore/tags/' + hashtag_list[tag] + '/')
sleep(5)
有什么建议吗这不是全部代码,但我想这就是我所需要的。-如果需要任何其他信息,请告诉我Python列表已归零索引。这意味着列表的第一个索引从
0
开始。因此hastag_list
的索引是0,1,2
。但是,randint(1,3)
是包含的,因此tag
有时会随机分配3
应该开始弄清楚问题是什么。由于hashtag\u list
的最大索引是2
,而tag
有时是3
,因此有时您将索引hashtag\u list
超出范围
简单的解决方案是使用randint(0,2)
而不是randint(1,3)
。然而,一个更干净的解决方案是从标签列表中选择一个随机选项:
from random import choice
# ...
hashtag_list = ['urban', 'hipster', 'retro']
for hashtag in hashtag_list:
tag = choice()
driver.get('https://www.instagram.com/explore/tags/' + hashtag_list[tag] + '/')
sleep(5)
randint(a,b)
生成范围[a,b]
内的随机整数,这些整数有时不起作用时生成3
,而3
超出了列表范围。将其更改为randint(0,2)
,因为在Python(和许多其他语言)中,包含n
元素索引的列表从0
开始,并在n-1
结束。因此:
# elements: ['urban', 'hipster', 'retro']
# indices: 0 1 2
改变
tag=randint(1,3)
到
tag=randint(0,2)在pythonindex中,列出从0开始的索引,使用randint(0,2)