So I have this code:
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
I want to make a two-dimensional list of difference in scores between each pair of teams. The output can be like this:
What is the easiest way to do this? Thanks :)
You could try:
[[x[1]-y[1] for y in TeamList] for x in TeamList]
That will generate a nested list representing the proposed output (without the column and row headings, of course).
Just using tabs rather than any fancy formatting to build the chart:
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
# print the top row of team names, tab separated, starting two tabs over:
print '\t\t', '\t'.join(team[0] for team in TeamList)
# for each row in the chart
for team in TeamList:
# put two tabs between each score difference column
scoreline = '\t\t'.join(str(team[1] - other[1]) for other in TeamList)
# and print the team name, a tab, then the score columns
print team[0], '\t', scoreline
You could try nested for loop. Something like this:-
for team1 in TeamList:
for team2 in TeamList:
print team1[1]-team2[1]
This will give the score difference. The output will have to be formatted to get the exact table look that you want.
A list comprehension would work (but nested list comprehensions don't sit quite right with me.) itertools.product()
is another way.
Consider the following as food for thought:
import itertools
scores = {
"Red" : 10,
"Green" : 5,
"Blue" : 6,
"Yellow": 8,
"Purple": 9,
"Brown" : 4,
}
for team_1, team_2 in itertools.product(scores, scores):
print ("Team 1 [%s] scored %i, Team 2 [%s] scored %i." % (team_1, scores[team_1], team_2, scores[team_2]) )
Which outputs:
Team 1 [Blue] scored 6, Team 2 [Blue] scored 6.
Team 1 [Blue] scored 6, Team 2 [Brown] scored 4.
... (32 more lines) ...
Team 1 [Red] scored 10, Team 2 [Green] scored 5.
Team 1 [Red] scored 10, Team 2 [Red] scored 10.
Team1 = ["Red", 10]
Team2 = ["Green", 5]
Team3 = ["Blue", 6]
Team4 = ["Yellow", 8]
Team5 = ["Purple", 9]
Team6 = ["Brown", 4]
TeamList = [Team1, Team2, Team3, Team4, Team5, Team6]
# calculate scores
scores = [[x[1]-y[1] for y in TeamList] for x in TeamList]
# print the top row of team names, tab separated, starting two tabs over:
print('\t\t', '\t'.join(team[0] for team in TeamList))
# for each row in the chart
for score, team in zip(scores,TeamList):
print(("%s"+"\t%s"*len(TeamList)) % ((team[0],)+tuple(score)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.