Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - Don't understand cause of TypeError in my bingo game simulator

It gives me this error:

    for s in lista[pl]["schede"]:
TypeError: list indices must be integers or slices, not dict

Python code:

#import
import random
#---------------
#data
list1 = []
extracted = {"tot":0,"number":[]}
cards = int(input("# cards= "))
player = int(input("# player= "))
winner = ' '
#---------------
#code
for pl in range(player):
    name = input("enter player name= ")
    list1.append({"name": name, "cards":[]})
    for sc in range(cards):
        list1[pl]["cards"].append([])
        i = 0
        while i != 15:
            num = random.randint(1, 90)
            if not num in list1[pl]["cards"][sc]:
                list1[pl]["cards"][sc].append(num)
                i += 1
for n in range(90):
    num = random.randint(1, 90)
    if not num in extracted["number"]:
        extracted["tot"] += 1
        extracted["number"].append(num)
        for pl in list1:
            **for s in list1[pl]["cards"]:**
                for e in list1[pl]["cards"][s]:
                    if num in list1[pl]["cards"][s]:
                        list1[pl]["cards"][s][list1[pl]["cards"][s].index(num)] = 0
                        if sum(list1[pl]["cards"][s]) == 0:
                            winner = list1[pl]["name"]
print("The winner is=",winner,"
The numbers drawn are=",extracted["tot"])
question from:https://stackoverflow.com/questions/66066652/dont-understand-cause-of-typeerror-in-my-bingo-game-simulator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're already getting each pl dictionary from list1 via:

for pl in list1:

You can't use a list's item as a list index. So, list1[pl] will fail since pl is a dictionary. It's unnecessary to do list1[pl] since pl is already an item from list1.

You just need to do this:

for pl in list1:
  for s in pl["cards"]:

So, everywhere else where you're doing list1[pl], you need to replace it with just pl.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...