maisui童鞋 maisui童鞋 - 1 month ago 7
Python Question

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

Answer

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)
Comments