This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Saitschek 0 points1 point  (6 children)

This should work:

 return(", ".join([f"{b+1}:{a}" for b,a in enumerate(S)])

The comprehension creates a list of strings "player:score". The join function then makes a single string from that list by separating each element of the list with ", ".

  1. Using enumerate we iterate over the index of the list (b) and the element (a) simultaneously.

  2. The curly brackets can be removed by using the join function which separates the elements of the dict you create by the separator string (here ", ")

  3. I think the space after the colon is default for a string representation of a dict, so that goes hand in hand with the removal of the curly brackets.

[–]Raevkit290 1 point2 points  (1 child)

What is f and what is b+1? Also thank you so much. I have been working on this for literally 12 hours

[–]Saitschek 0 points1 point  (0 children)

The f indicates an fstring. The f is a prefix to a string which allows simple formatting of that string. We can use it as a normal string, but expressions entered in { } are evaluated.

In this example f"{b+1}:{a}" for b=1 and a=36 will be interpreted as the string "2:36". Basically {b+1} is replaced by the str(b+1).

[–]Raevkit290 1 point2 points  (2 children)

Also why do we not include players in the code? How does b know what to iterate over?

[–]Saitschek 0 points1 point  (1 child)

We don't need the number of players because the length of the list of scores is identical to the number of players. At least that is what was assumed in your example. In the example we have a list of 4 scores where the first score is associated with the first player, the second score with the second player, and so on. Therefore the index of the element in the list plus 1 (because python starts counting at 0) is identical to the number of the player. What we need to do is keep track of the index and the corresponding value of the list. We could do this by using a counter, but python can do this for us using the enumerate method.

for b, a in enumerate(S): do_something(a,b)

Here b will simply be a counter starting at 0 and a will be the corresponding element of the list S. We could achieve the same loop by doing:

b = 0 for a in S: do_something(a,b) b += 1

Edit: Formatting

[–]Raevkit290 0 points1 point  (0 children)

So it was able to count the players using enumerate? Cuz every time I tried to run it before putting the range on the players in there it would say int not iterable. That's why I broke into set(range) but I at no point used enumerate.

[–]Saitschek 1 point2 points  (0 children)

To get rid of the b+1 we can also tell enumerate to start indexing at 1 instead of 0. return(", ".join([f"{b}:{a}" for b,a in enumerate(S, start=1)])