简体   繁体   English

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

[英]Creating new lists from dictionaries nested within list

I was tasked with taking this list (Players):我的任务是列出这份名单(球员):

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

And split it up into even teams, not only by quantity of players but also by a number of experienced players.并将其分成均匀的球队,不仅是根据球员的数量,还包括一些经验丰富的球员。 So all teams had the same number of "non-experienced" players and "Experienced players".所以所有球队都有相同数量的“非经验”球员和“经验丰富的球员”。 I was able to split the teams into equal teams pretty easily, but when it came to ensuring all teams had the same number of experienced players, It lost me.我能够很容易地将球队分成平等的球队,但是当谈到确保所有球队拥有相同数量的经验丰富的球员时,它让我失望了。 Below was my thought process, I thought I could copy the 'PLAYERS' list break that into an experienced list (exp_players) and non-experienced list (nexp_players), but it's backfiring on me.以下是我的思考过程,我想我可以将“球员”列表复制为有经验的列表(exp_players)和非经验列表(nexp_players),但这对我来说适得其反。 Even though this is no the most efficient way to do it, but I thought it should work.尽管这不是最有效的方法,但我认为它应该有效。 But there has to be a simpler way to do this and I just can't see it.但是必须有一种更简单的方法来做到这一点,而我只是看不到它。 Here's the error I'm getting for my current code:这是我当前代码遇到的错误:

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)  

My expected output would be the three teams (panthers, bandits and warriors) would have equal amount of players and equal players that experience == True.我预期的 output 将是三支球队(黑豹、土匪和勇士)将拥有相同数量的球员和相同的球员经验 == True。

As i see it you will have to move those variables:如我所见,您将不得不移动这些变量:

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

to this line of code:到这行代码:

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

By doing this i think that you will not get the error name.... is not defined通过这样做,我认为您不会得到错误name.... is not defined

You imported random , but I don't see it being used.您导入了random ,但我没有看到它被使用。 But yes, that's how I was thinking about it.但是,是的,我就是这么想的。

First thing you need is to seperate the experienced players from non-experienced.您需要做的第一件事是将有经验的玩家与没有经验的玩家区分开来。 Then you could use random to randomly select a player (without replacement) from each list (exp and nexp) and place them into a team individually 1 by 1.然后,您可以使用随机到随机 select 每个列表(exp 和 nexp)中的一个玩家(无需替换)并将他们逐个放入一个团队中。

Or use random to partition those 2 lists into n number of teams.或者使用随机将这 2 个列表分成 n 个团队。 I chose this way.我选择了这种方式。

So first split the list of players into a experienced list and not experienced list.所以首先将玩家列表拆分为有经验的列表和没有经验的列表。 Shuffle each of those lists so its random.随机播放这些列表中的每一个,使其随机。 Then partitioned each list into a list of 3 (because there are 3 teams).然后将每个列表划分为 3 个列表(因为有 3 个团队)。 1st group goes into team 1, 2nd group into team 2, and 3rd group into team 3, etc. And you just do that for the experienced and non-experienced lists.第 1 组进入第 1 组,第 2 组进入第 2 组,第 3 组进入第 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')

Output: Output:

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

You then have preserved any data wanted for the players in json format:然后,您以 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'}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM