列出索引超出范围和随机数以选择列表中的项目

Reg*_*ser 0 python random split list

我需要使用字符串制作一个iPhone模型列表.split().

这不是问题,但我还必须使用0-9中的随机数来挑选一个单词,然后使用while/for循环显示3个随机单词.

在我的代码中,当我输入:

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])
Run Code Online (Sandbox Code Playgroud)

它说:

 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
Run Code Online (Sandbox Code Playgroud)

我不确定是什么造成的.

iCo*_*dez 5

这两个论点random.randint都是包容性的:

>>> import random
>>> random.randint(0, 1)
1
>>> random.randint(0, 1)
0
>>>
Run Code Online (Sandbox Code Playgroud)

所以,当你这样做时x = random.randint(0,10),x有时可能等于10.但是您的列表iPhone只有十个项目,这意味着最大索引是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
>>>
Run Code Online (Sandbox Code Playgroud)

你需要这样做:

x = random.randint(0, 9)
Run Code Online (Sandbox Code Playgroud)

所以它x总是在有效索引的范围内iPhone.


关于你的评论,你说你需要从列表中打印三个随机项目.所以,你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)