Fatal Rein Fatal Rein - 1 month ago 4
Python Question

Remove brackets [] from list (while sorting with key)

What i am after: instead of having a list output like this:

['test1', 'test2', test3']


i would want it to output like this:

test1 | test2 | test3
or this is fine too
test1, test2, test3


My code: right now this is how it looks like:

deelnemers = []
# i add name, csgo and score to deelnemers[] via class Deelnemer
deelnemers.append(Deelnemer(naam, int(csgo), int(score)))

# key to sort it by csgo value
def keyCSGO(deelnemer):
return deelnemer.csgo

# i print it in reverse so the highest csgo number will be first
print("\nNaam | CSGO Score\n----------------\n", sorted(deelnemers, key=keyCSGO, reverse=True))


What i have tried:

print(", ".join("\nNaam | CSGO Score\n----------------\n", sorted(deelnemers, key=keyCSGO, reverse=True)))


so obviously the above gives that you can have only 1 argument with .join:
join() takes exactly one argument (2 given)


so i removed the naam | csgo part to test it out:

print(", ".join(sorted(deelnemers, key=keyCSGO, reverse=True)))


but now i get this exception:
sequence item 0: expected str instance, Deelnemer found


i think i am looking in the wrong direction, so i am not sure where to look at to have [ '' ] removed from a list. Thank you for the help and advice.

Answer

You can only join strings, so you probably need to access the name attribute (assuming that what it is) of each instance after sorting to use them in join:

print(", ".join(d.name for d in sorted(deelnemers, key=keyCSGO, reverse=True)))

You can also put the attributes in a string before joining using string formatting (credits @Tadhg):

", ".join("{0.name} {0.csgo} {0.score}".format(d) for d in sorted(deelnemers, key=keyCSGO, reverse=True))
Comments