简体   繁体   中英

Generating a list of random integers in python 3

I am getting a IndexError: list assignment index out of range error when trying to run this program. My index appears to be fine (0 through 8) and I don't think .append is needed since the equal sign assign the random value each pass. What am I missing?

import random

#The main function.
def main():

  #Welcome message.
  print("Welcome to the lottery number generator program!")
  print()

  #Explain what the program does.
  print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
  print("________________________________________________________________________________________________")
  print()
  print()

  #Call the generateNumbers function and store its returned list in variable lotteryNumbers.
  lotteryNumbers = generateNumbers()

  #Call the printLottery function and pass the lotteryNumbers list as argument.
  printLottery(lotteryNumbers)


#The generateNumbers function generated 7 random digits between 0  and 9 stores them in a list and returns the list.
def generateNumbers():

  #A list variable to hold empty list.
  lotteryNumbers = []

  #Declare and set loop counter to 0.
  index = 0

  for index in range (0,8):
    lotteryNumbers[index] = random.randrange(0,10)
    index += 1
  return lotteryNumbers


def printLottery(lotteryNumbers):
  print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))

#End main
main()

Lists are not like arrays in other languages!

lotteryNumbers is initialised as an empty list. There is nothing in it. Its length is zero. You need to add random.randrange(0, 10) to the empty list. This is done through .append()

  for index in range (0,8):
    lotteryNumbers[index] = random.randrange(0,10)
    index += 1

This doesn't do what you're hoping it does. You can't assign a value to a position that doesn't currently exist in a list, and as that list is currently empty, that means you can't do this at all.

what you want is:

for index in range (0,8):
    lotteryNumbers.append(random.randrange(0,10))

You don't need index += 1 because python handles this for you int the for loop.


by the way, lotteries are generally picked without replacement, so don't you actually want to sample?

https://docs.python.org/2/library/random.html#random.sample

eg:

lotteryNumbers = random.sample(xrange(10), 7)

although it is also normal for lotteries to have far more than 10 options!

You should append the new values:

def generateNumbers():

  #A list variable to hold empty list.
  lotteryNumbers = []

  #Declare and set loop counter to 0.
  index = 0

  for _ in range (0,8):
    lotteryNumbers.append(random.randrange(0,10))
  return lotteryNumbers

or build the list up to the size you want:

def generateNumbers():

  #A list variable to hold empty list.
  lotteryNumbers = [0]*8

  #Declare and set loop counter to 0.
  index = 0

  for index in range (0,8):
    lotteryNumbers[index] = random.randrange(0,10)
  return lotteryNumbers

Also notice you dont neet to increment the index, you are already iterating through the range.

You are trying to access non-existing elements of the list.

To build your list, you can either keep appending to it with list.append() :

lotteryNumbers = []
for _ in range(8):
    lotteryNumbers.append(random.randrange(0,10))

or, as it's common in Python, use a list comprehension :

lotteryNumbers = [random.randrange(0,10) for _ in range(8)]

which is usually more efficient and succinct.

我认为您尝试将元素添加到数组

lotteryNumbers = [0,0,0,0,0,0,0]

By initializing an list with

lotteryNumbers = []

it has exactly 0 elements. But with

lotteryNumbers[index] = random.randrange(0,10)

You try to access the 1st, the 2nd, .. , nth element of the list. Your code does not insert elements to the list. To avoid this there are serveral approaches.

  • Create a dict instead of a list. A dict actually creates nonexistent elements: lotteryNumbers = {}
  • Preinitialize the list with 8 elements:
    • lotteryNumbers = [0,0,0,0,0,0,0,0]
    • or lotteryNumbers = list(range(8))
  • But the most preferable variant should be to use append: lotteryNumbers.append(random.randrange(0,10))

This works. Make an array with the numbers you want and select randomly one item. Then, delete that item and decrease the length with one (using pop). In this example the numbers 1 till 7

lotteryNumbers = []
rij = []
for i in range(aantal):
    rij.append(i)
for j in range(7):
    r = random.randrange(0,7-j)
    k = rij.pop(r)
    lotteryNumbers.append(k+1)
print(lotteryNumbers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM