maisui童鞋
maisui童鞋

Reputation: 13

how to make a random list in python3

i just want make a list to display students scores and different course have different scores ,the scores comes from.random randint(70,100), like this:

[{'C++':70,'Math':80,'Python':90},
{'C++':87,'Math':82,'Python':91},...]

import random
def makedict(spam):
    a=[]
    for j in range(20):             
        for i in spam:
        a[j].setdefault(i,random.randint(70,90))
    return a
if __name__=="__main__":
    cou=['C++','Math',Python]
    res=makedict(cou)

IndexError: list index out of range how i change the code

Upvotes: 1

Views: 175

Answers (3)

Rahul K P
Rahul K P

Reputation: 16081

Try this, You have to use append.

import random
def makedict(spam):
    result = []
    for _ in range(20):
        result.append({j:random.randint(70,90) for j in spam})
    return result

if __name__=="__main__":
    cou=['C++','Math', 'Python']
    res=makedict(cou)

Upvotes: 0

Jerome Anthony
Jerome Anthony

Reputation: 8021

Your indentation for the second for..loop is wrong. Fix it and it will work.

Upvotes: 0

Dror Hilman
Dror Hilman

Reputation: 7457

use dictionary comprehension

import random
def makedict(subjects):
    return {s: random.randint(70,100) for s in subjects}

if __name__=="__main__":
    cou=['C++','Math','Python']
    res=makedict(cou)

Upvotes: 2

Related Questions