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
243 views
in Technique[技术] by (71.8m points)

python - Search 3D list for single Item

I am creating a leaderboard creating system, where it checks if the Name is already in the Database, if not it adds it, and if it is it replaces the name and score.

import csv
winner =["Player", 100]
def leaderboardsave(winner):
    fileCSV = open('scores.csv')
    dataCSV = csv.reader(fileCSV)
    playersScores = list(dataCSV)
    winnerName = winner[0]
    winner_index = playersScores.find(winnerName)
    if winner_index > -1:
        playersScores[winner_index] = winner
    else:
        playersScores.append(winner)
leaderboardsave(winner)

The CSV is saved like this:

Player, 20
Player2, 40
Player3, 30
Player4, 60

whenever I run

    winner_index = playersScores.find(winnerName)

it returns "'list' object has no attribute 'find'" Any other ways to find where the item is in the list? When i tried using .index, it wouldnt find it, i assume as it is looking for a list, not a single string?


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

1 Answer

0 votes
by (71.8m points)

You are getting that error because playerScores is a list object and a list object doesn't have a find function.

You can traverse a list to find a value by looping:

winner_index = [index for index, value in enumerate(playerScores) if value == winnerName]


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

...