从嵌套在列表中的词典创建新列表

2024-05-15 04:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是获取以下列表(玩家):

https://github.com/josephyhu/Basketball-Team-Stats-Tool/blob/master/constants.py

并将其分成两队,不仅根据球员数量,还根据经验丰富的球员数量。因此,所有球队都有相同数量的“无经验”球员和“有经验”球员。我可以很容易地将球队分成相等的队伍,但当涉及到确保所有球队都有相同数量的经验丰富的球员时,我就输了。下面是我的思考过程,我想我可以复制“玩家”名单,将其分为经验丰富的玩家(exp_玩家)和无经验的玩家(nexp_玩家),但结果适得其反。尽管这不是最有效的方法,但我认为它应该有效。但必须有一个更简单的方法来做到这一点,我就是看不出来。以下是我当前代码的错误:

Traceback (most recent call last):                                                                                               
  File "/home/treehouse/workspace/123.py", line 25, in <module>                                                                  
    panthers = exp_panthers + nexp_panthers                                                                                      
NameError: name 'exp_panthers' is not defined
import random
from constants import PLAYERS
from constants import TEAMS

GREETING = 'BASKETBALL TEAM STATS TOOL\n'

players = PLAYERS.copy()
teams = TEAMS.copy()

print(GREETING.upper())


print('-----MENU-----\n')

panthers = exp_panthers + nexp_panthers
bandits = exp_bandits + nexp_bandits
warriors = exp_warriors + nexp_warriors

exp_players = []
nexp_players = []
max_eplayers = len(exp_players)/len(teams)
max_neplayers = len(nexp_players)/len(teams)


exp_panthers=[]
exp_bandits= []
exp_warriors=[]
nexp_panthers=[]
nexp_bandits= []
nexp_warriors=[]

def count_exp(players):
    for player in players:
        if player['experience'] == True:
            exp_players.append(player)
        else:
            nexp_players.append(player)

def balance_team_exp(exp_players):
    for player in exp_players:
        player_name = player['name']

        if len(panthers) < max_players:
            exp_panthers.append(player_name)
        elif len(bandits) < max_players:
            exp_bandits.append(player_name)
        elif len(warriors) < max_players:
            exp_warriors.append(player_name)

def balance_team_nexp(nexp_players):
    for player in nexp_players:
        player_name = player['name']

        if len(panthers) < max_players:
            nexp_panthers.append(player_name)
        elif len(bandits) < max_players:
            nexp_bandits.append(player_name)
        elif len(warriors) < max_players:
            nexp_warriors.append(player_name)  

我的预期输出将是三支球队(黑豹队、土匪队和勇士队)拥有同等数量的球员,并且拥有同等经验==真实的球员


Tags: name数量len玩家经验maxbanditsplayer
2条回答

在我看来,你必须移动这些变量:

exp_panthers=[]
exp_bandits= []
exp_warriors=[]

对于这一行代码:

exp_panthers=[]
exp_bandits= []
exp_warriors=[]
nexp_panthers=[]
nexp_bandits= []
nexp_warriors=[]
panthers = exp_panthers + nexp_panthers
bandits = exp_bandits + nexp_bandits
warriors = exp_warriors + nexp_warriors

通过这样做,我认为您不会得到错误name .... is not defined

您导入了random,但我看不到正在使用它。但是是的,我就是这么想的

你需要做的第一件事就是把有经验的球员和没有经验的球员分开。然后,您可以使用random从每个列表(exp和nexp)中随机选择一个玩家(无需替换),然后逐个将他们放入一个团队

或者使用random将这两个列表划分为n个团队。我选择了这条路

因此,首先将玩家名单分为有经验和无经验两部分。将每个列表洗牌,使其随机。然后将每个列表划分为3个列表(因为有3个团队)。第一组进入第1组,第二组进入第2组,第三组进入第3组,等等。你只需要对有经验和无经验的列表进行操作

import random
from constants import PLAYERS
from constants import TEAMS

GREETING = 'BASKETBALL TEAM STATS TOOL\n'

players = PLAYERS.copy()
teams = TEAMS.copy()

print(GREETING.upper())


print('  -MENU  -\n')


# Split players into exp and nexp
def split_into_exp_nexp_players(players_list):
    exp_players = []
    nexp_players = []
    for player in players_list:
        if player['experience'] == 'YES':
            exp_players.append(player)
        else:
            nexp_players.append(player)
            
    return exp_players, nexp_players


# Function that will split a list into equal n lists
# credit: https://stackoverflow.com/questions/3352737/how-to-randomly-partition-a-list-into-n-nearly-equal-parts
def partition (list_in, n):
    random.shuffle(list_in)
    return [list_in[i::n] for i in range(n)]


# Using that function above, create the equal splits into n teams
def split_into_teams(teams, exp_players, nexp_players):
    exp_split = partition(exp_players, len(teams))
    nexp_split = partition(nexp_players, len(teams))
        
    return exp_split, nexp_split


exp_players, nexp_players = split_into_exp_nexp_players(players)
exp_players, nexp_players = split_into_teams(teams, exp_players, nexp_players)


# Put each of those partitioned players into teams
team_rosters = {}
for idx, team in enumerate(teams):
    comb_players = exp_players[idx] + nexp_players[idx]
    team_rosters[team] = comb_players
    

for team, roster in team_rosters.items():
    print('%s:' %team)
    for each_player in roster:
        print(each_player['name'], each_player['experience'])
        
    print('\n')

输出:

Panthers:
Bill Bon YES
Herschel Krustofski YES
Diego Soto YES
Kimmy Stein NO
Sammy Adams NO
Eva Gordon NO


Bandits:
Jill Tanner YES
Phillip Helm YES
Suzane Greenberg YES
Ben Finkelstein NO
Matt Gill NO
Sal Dali NO


Warriors:
Karl Saygan YES
Joe Smith YES
Les Clay YES
Arnold Willis NO
Joe Kavalier NO
Chloe Alaska NO

然后,您以json格式为玩家保留了所需的任何数据:

print(team_rosters)
{'Panthers': [{'name': 'Bill Bon', 'guardians': 'Sara Bon and Jenny Bon', 'experience': 'YES', 'height': '43 inches'}, {'name': 'Herschel Krustofski', 'guardians': 'Hyman Krustofski and Rachel Krustofski', 'experience': 'YES', 'height': '45 inches'}, {'name': 'Diego Soto', 'guardians': 'Robin Soto and Sarika Soto', 'experience': 'YES', 'height': '41 inches'}, {'name': 'Kimmy Stein', 'guardians': 'Bill Stein and Hillary Stein', 'experience': 'NO', 'height': '41 inches'}, {'name': 'Sammy Adams', 'guardians': 'Jeff Adams and Gary Adams', 'experience': 'NO', 'height': '45 inches'}, {'name': 'Eva Gordon', 'guardians': 'Wendy Martin and Mike Gordon', 'experience': 'NO', 'height': '45 inches'}], 'Bandits': [{'name': 'Jill Tanner', 'guardians': 'Mark Tanner', 'experience': 'YES', 'height': '36 inches'}, {'name': 'Phillip Helm', 'guardians': 'Thomas Helm and Eva Jones', 'experience': 'YES', 'height': '44 inches'}, {'name': 'Suzane Greenberg', 'guardians': 'Henrietta Dumas', 'experience': 'YES', 'height': '44 inches'}, {'name': 'Ben Finkelstein', 'guardians': 'Aaron Lanning and Jill Finkelstein', 'experience': 'NO', 'height': '44 inches'}, {'name': 'Matt Gill', 'guardians': 'Charles Gill and Sylvia Gill', 'experience': 'NO', 'height': '40 inches'}, {'name': 'Sal Dali', 'guardians': 'Gala Dali', 'experience': 'NO', 'height': '41 inches'}], 'Warriors': [{'name': 'Karl Saygan', 'guardians': 'Heather Bledsoe', 'experience': 'YES', 'height': '42 inches'}, {'name': 'Joe Smith', 'guardians': 'Jim Smith and Jan Smith', 'experience': 'YES', 'height': '42 inches'}, {'name': 'Les Clay', 'guardians': 'Wynonna Brown', 'experience': 'YES', 'height': '42 inches'}, {'name': 'Arnold Willis', 'guardians': 'Claire Willis', 'experience': 'NO', 'height': '43 inches'}, {'name': 'Joe Kavalier', 'guardians': 'Sam Kavalier and Elaine Kavalier', 'experience': 'NO', 'height': '39 inches'}, {'name': 'Chloe Alaska', 'guardians': 'David Alaska and Jamie Alaska', 'experience': 'NO', 'height': '47 inches'}]}

相关问题 更多 >

    热门问题