问题描述
我需要使用.split()
从字符串中列出iPhone型号.
I need to make a list of iPhone models from a string using .split()
.
这不是问题,但是我还必须使用0-9之间的随机数来选择一个单词,然后使用while/for循环显示3个随机词.
That's not a problem, but I also have to use a random number from 0-9 to pick a word,then display 3 random words using while/for loop.
在我的代码中,当我输入:
In my code, when I enter:
import random
iPhone = 'Original 3G 3GS 4 4S 5 5C 5S 6 6Plus'.split()
z = 0
while z < 4:
for y in range (1,3):
for x in iPhone:
x = random.randint(0,10)
print (iPhone[x])
它说:
Traceback (most recent call last):
File "C:\Users\zteusa\Documents\AZ_wordList2.py", line 15, in <module>
print (iPhone[x])
IndexError: list index out of range
我不确定是什么原因造成的.
I'm not sure whats causing this.
推荐答案
random.randint
的两个参数都包含在内:
Both arguments to random.randint
are inclusive:
>>> import random
>>> random.randint(0, 1)
1
>>> random.randint(0, 1)
0
>>>
因此,当您执行x = random.randint(0,10)
时,x
有时可能等于10
.但是您的列表iPhone
仅包含十个项目,这意味着最大索引为9
:
So, when you do x = random.randint(0,10)
, x
could sometimes be equal to 10
. But your list iPhone
only has ten items, which means that the maximum index is 9
:
>>> iPhone = 'Original 3G 3GS 4 4S 5 5C 5S 6 6Plus'.split()
>>> len(iPhone)
10
>>> iPhone[0] # Python indexes start at 0
'Original'
>>> iPhone[9] # So the max index is 9, not 10
'6Plus'
>>> iPhone[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
您需要这样做:
x = random.randint(0, 9)
,以便x
始终在iPhone
的有效索引范围内.
so that x
will always be within the range of valid indexes for iPhone
.
关于您的评论,您说您需要从列表中打印三个随机项目.因此,您可以执行以下操作:
Regarding your comments, you said that you need to print three random items from the list. So, you could do something like this:
import random
iPhone = 'Original 3G 3GS 4 4S 5 5C 5S 6 6Plus'.split()
z = 0
while z < 3:
x = random.randint(0,9)
print (iPhone[x])
z += 1 # Remember to increment z so the while loop exits when it should
这篇关于列出索引超出范围和随机数以选择列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!