I've 5 lists with some Infos saved in like:
list1 = [['Mark',18],['Lola',29]]
list2 = [['James' 33],['Mark',46]]
list3 = [['Lola',86],['Arnold',78]]
list4 = [['James',46],['Arnold',18]]
list5 = [['Mark',16], ['James',10]]
What i'd like do is check them and create a table like that's:
Name Score1 Score2 Score3
---- ------- ------- --------
Mark 18 46 16
Lola 29 86
Arnold 78 18
James 33 46 10
I've no worries to import a new library like pandas or others.
I tried to use some nested For loop to check if there's double values in each list and if was true, add it, but i've many trouble to get the by name (ex. List['James']) After some research seems that's Is not possibile to do in py.
Looking for any kind of solition to understand better.
CodePudding user response:
I would not recommend to store data in this way, i.e. dictionary can be a good solution for this situation. Anyway, if we assume, that you get this result from somewhere else, then you can do something like this:
scores = dict()
for i, lst in enumerate((list1, list2, list3, list4, list5), start=1):
for record in lst:
player_scores = scores.get(record[0], {})
player_scores[i] = record[1]
scores[record[0]] = player_scores
Then you can easily print from this dict or use in any other parts.
P.S. And yes, I don't like the look of the enumerate, too )
CodePudding user response:
Try:
from itertools import chain
list1 = [["Mark", 18], ["Lola", 29]]
list2 = [["James", 33], ["Mark", 46]]
list3 = [["Lola", 86], ["Arnold", 78]]
list4 = [["James", 46], ["Arnold", 18]]
list5 = [["Mark", 16], ["James", 10]]
tmp = {}
for name, score in chain.from_iterable([list1, list2, list3, list4, list5]):
tmp.setdefault(name, []).append(score)
max_scores = len(max(tmp.values(), key=len))
print(
"{:<15}".format("Name")
("{:<10}" * max_scores).format(
*[f"Score{i 1}" for i in range(max_scores)]
)
)
print(
"{:<15}".format("-" * 4)
("{:<10}" * max_scores).format(*["-" * 6 for _ in range(max_scores)])
)
for k, v in tmp.items():
print("{:<15}".format(k), end="")
print(("{:<10}" * len(v)).format(*[str(i) for i in v]))
Prints:
Name Score1 Score2 Score3
---- ------ ------ ------
Mark 18 46 16
Lola 29 86
James 33 46 10
Arnold 78 18