python 尝试使用IF语句追加数组

vq8itlhq  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(160)
firstTeamPlace = [] # This is for where the team placed, 1st, 2nd, 3rd etc
firstTeamTotal = []# This is where the scores are added to make a final score

m = {
    "1": 4,
    "2": 3,
    "3": 2,
    "4": 1,
}
def firstTeamPoints():
    firstTeamTotal.append(m[firstTeamPlace])
        
def tevent1():
    print("This is the relay race event")
    print("Please enter the where each team placed next to their name (1-4)")
    eventaFirstTeam = input(tnames[0])
    firstTeamPlace.append(eventaFirstTeam)

    eventaSecondTeam = input(tnames[1])
    secondTeamPlace.append(eventaSecondTeam)

    eventaThirdTeam = input(tnames[2])
    thirdTeamPlace.append(eventaThirdTeam)

    eventaFourthTeam = input(tnames[3])
    fourthTeamPlace.append(eventaFourthTeam)
    print(firstTeamTotal)

firstTeamTotal数组没有被添加到它应该被添加的地方。Idk如何使数组被追加。
我是否只需要创建一个数组

sirbozc5

sirbozc51#

简化您的逻辑:

def firstTeamPoints():
    firstTeamTotal.append(5 - int(firstTeamPlace))

如果事实证明它更复杂,你可以使用一个Map:

m = {
    "1": 4,
    "2": 3,
    "3": 2,
    "4": 1,
}
def firstTeamPoints():
    firstTeamTotal.append(m[firstTeamPlace])
rdlzhqv9

rdlzhqv92#

您可以以更快、更灵活的方式完成您想做的事情:

#Some preparation. You can do it manually or with another function

tnames = ['team 1', 'team 2', 'team 3', 'team 4', 'team 5'] 
teamsPlaces = [] # This is for where the teams placed for each event, 1st, 2nd, 3rd etc
teamsTotals = [] # This is where the scores are added to make a final score for each team

#Here we prepare the final scores, with everyone starting from 0
for team in range(len(tnames)):
    teamsTotals.append(0)

def tevent1():
    print("This is the relay race event")
    print("Please enter the where each team placed next to their name (1-4)")
    eventTeamsPlaces = []
    for i in range(len(tnames)):
        teamPos = input(tnames[i])
        eventTeamsPlaces.append(teamPos) #for each event, you will have a list of places
        teamsTotals[i] = teamsTotals[i] + (len(tnames) - int(teamPos))
        
    teamsPlaces.append(eventTeamsPlaces) #and the list of places is appended to the list of places for all the events
    print(teamsTotals)
tevent1()

这样,在两个事件结束后,您的输出为:

teamsPlaces = [['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
teamsTotals = [4, 4, 4, 4, 4]

end如果您想获得事件编号2的地点列表,您可以使用teamsPlaces[1],即['5', '4', '3', '2', '1']
通过这种方法,您可以对所有事件使用这个简单的函数,而对团队数量和事件数量没有任何限制。

相关问题