Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 索引器:列表索引超出范围-有时运行,有时不运行_Python_Python 3.x - Fatal编程技术网

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)