Reputation: 331
Okay, technically I have been assigned a task to complete and it involves loops (while, for, etc.) and I have come across a problem:
I was asked to store the scores and username, level etc. in a list format like this:
# <username>, <level>, <level_score> - Like this:
['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
What I need to do is create a scoreboard using this data, but I cannot seem to isolate the scores from the string in the list. Here is a snippet of my code:
def scoreboard():
name = input("Enter a username: ") # Say 'buzzysin'
t = open('scores.txt', 'r')
a = t.readlines()
b = []
t.close()
for i in range(len(a)):
if name not in a[i]:
pass
else: # Here I need to get the occurences of 'buzzysin' and append it to b
b.append(a[i])
#Then I need to extract the level and scores, but here's where I'm stuck :-(
My scoreboard need to look like this:
>>> scoreboard()
Please enter a name: buzzysin
The scores for buzzysin are:
Level Scores
-----------------------
1 10
2 0
3 0
4 0
5 100
>>>
Please help,
'buzzysin'
Upvotes: 2
Views: 98
Reputation: 1779
# get all scoreboard data
data = ['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
# get target name
target_name = input("Enter a username: ")
# initialize our target scoreboard
target_scoreboard = {}
# get scoreboard data for our target
for name_data in data: # look at all the data, one item at a time
if name_data.split(',')[0] == target_name:
# if this data is for our target, add it to out target scoreboard
level = int(name_data.split(',')[1])
score = int(name_data.split(',')[2])
target_scoreboard[level] = score
# print scoreboard for our target, sorted by level
print("\tLevel\tScore")
print("-"*25)
for level in sorted(target_scoreboard):
print('\t{:d}\t{:d}'.format(level, target_scoreboard[level]))
Upvotes: 0
Reputation: 10513
First of all, for i in len(a)
will raise an exception, since integers are not iterable. You either should directly iterate a
or iterate a list of indices like range(len(a))
. Secondly, if lines in a
are formatted as follows buzzysin,5,100
you should use the string.startswith
intead of in
(saves a hell lot of time). And then, if a string starts with buzzysin, you can parse that string with string.split(',')
to get the score. For instance,
for line in a:
if line.startswith(player_name):
name, level, score = line.rstrip().split(',')
Upvotes: 2
Reputation: 8721
Go modular! Write a separate function for parsing each line, use it to parse all of the lines, and then filter out the scores for the relevant person. List comprehensions are great for this:
def parse_line(line):
"""parse a score line, returning its data
A score line is of the form: <username>,<level>,<level_score>
The level and score are integers.
"""
parts = line.split(',')
if len(parts) != 3:
return None # or raise an exception
name = parts[0]
level = int(parts[1])
level_score = int(parts[2])
return name, level, level_score
# read the lines
with open('scores.txt', 'r') as t:
lines = t.readlines()
# parse the lines, ignoring empty lines
scores = [parse_line(line) for line in lines if line != ""]
# get the person's name
name = input("Enter a username: ") # Say 'buzzysin'
# filter that person's scores
persons_scores = [score for score in scores if score[0] == name]
# now print your table...
Upvotes: 0
Reputation: 28636
Just use .split(',')
:
lines = ['buzzysin,5,100','apple_maple,3,60','choco_charlie,2,25','buzzysin,1,10']
for line in lines:
name, level, score = line.split(',')
print(name, 'is in level', level, 'with score', score)
Prints:
buzzysin is in level 5 with score 100
apple_maple is in level 3 with score 60
choco_charlie is in level 2 with score 25
buzzysin is in level 1 with score 10
Upvotes: 0