Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List calculation
#1
I just want to see if I can do the following code in a different and less repetitive way.
Thansk.

if Ranking_Maths[0]==Teams[0]:
    Team1point=Team1point+Maths[0]
elif Ranking_Maths[0]==Teams[1]:
    Team2point=Team2point+Maths[0]
elif Ranking_Maths[0]==Teams[2]:
    Team3point=Team3point+Maths[0]
else:
    Ranking_Maths[0]==Teams[3]:
    Team4point=Team4point+Maths[0]

if Ranking_Maths[1]==Teams[0]:
    Team1point=Team1point+Maths[1]
elif Ranking_Maths[1]==Teams[1]:
    Team2point=Team2point+Maths[1]
elif Ranking_Maths[1]==Teams[2]:
    Team3point=Team3point+Maths[1]
else:
    Ranking_Maths[1]==Teams[3]:
    Team4point=Team4point+Maths[1]

if Ranking_Maths[2]==Teams[0]:
    Team1point=Team1point+Maths[2]
elif Ranking_Maths[2]==Teams[1]:
    Team2point=Team2point+Maths[2]
elif Ranking_Maths[2]==Teams[2]:
    Team3point=Team3point+Maths[2]
else:
    Ranking_Maths[2]==Teams[3]:
    Team4point=Team4point+Maths[1]

if Ranking_Maths[3]==Teams[0]:
    Team1point=Team1point+Maths[3]
elif Ranking_Maths[3]==Teams[1]:
    Team2point=Team2point+Maths[3]
elif Ranking_Maths[3]==Teams[2]:
    Team3point=Team3point+Maths[3]
else:
    Ranking_Maths[3]==Teams[3]:
    Team4point=Team4point+Maths[3]
Output:
Teams ['A', 'B', 'C', 'D'] ---------------------------------------- Maths [15, 12, 10, 8] English [14, 13, 12, 11] History [13, 12, 11, 10] Academic [8, 9, 7, 6] Sport [8, 7, 6, 5] ---------------------------------------- Ranking_Maths ['A', 'B', 'C', 'D'] Ranking_English ['B', 'C', 'D', 'A'] Ranking_History ['C', 'D', 'A', 'B'] Ranking_Academic ['D', 'A', 'B', 'C'] Ranking_Sprorts ['B', 'C', 'D', 'A']
Reply
#2
Please show enough code to make code runnable.
Reply
#3
You can start with this:
Team1Points = Maths[Ranking_Maths.index(Team[0])]
Team2Points = Maths[Ranking_Maths.index(Team[1])]
Team3Points = Maths[Ranking_Maths.index(Team[2])]
Team4Points = Maths[Ranking_Maths.index(Team[3])]
Then you realize that TeamPoints should be a dictionary instead of individual variables.
TeamPoints = {'A':0, 'B':0, 'C':0, 'D':0}
Scores = [
    [15, 12, 10, 8],
    [14, 13, 12, 11],
    [13, 12, 11, 10],
    [8, 9, 7, 6],
    [8, 7, 6, 5]]
Rankings = [
    ['A', 'B', 'C', 'D'],
    ['B', 'C', 'D', 'A'],
    ['C', 'D', 'A', 'B'],
    ['D', 'A', 'B', 'C'],
    ['B', 'C', 'D', 'A']]
 
for team in TeamPoints:
    for score, rank in zip(Scores, Rankings):
        TeamPoints[team] += score[rank.index(team)]
 
for team, points in TeamPoints.items():
    print(team, points)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  calculation with list in list gianniskampanakis 13 4,598 Aug-09-2019, 12:01 PM
Last Post: gianniskampanakis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020