从列表中删除 和 [ ]



我的任务是删除"and"从"监护人"之间;字典中的键。下面是嵌套在列表中的字典:

PLAYERS = [{
'name': 'Karl Saygan',
'guardians': 'Heather Bledsoe',
'experience': 'YES',
'height': '42 inches'
},
{
'name': 'Matt Gill',
'guardians': 'Charles Gill and Sylvia Gill',
'experience': 'NO',
'height': '40 inches'
},
{   'name': 'Sammy Adams',
'guardians': 'Jeff Adams and Gary Adams',
'experience': 'NO',
'height': '45 inches'
},
{
'name': 'Chloe Alaska',
'guardians': 'David Alaska and Jamie Alaska',
'experience': 'NO',
'height': '47 inches'
},
{
'name': 'Bill Bon',
'guardians': 'Sara Bon and Jenny Bon',
'experience': 'YES',
'height': '43 inches'
},
{
'name': 'Joe Kavalier',
'guardians': 'Sam Kavalier and Elaine Kavalier',
'experience': 'NO',
'height': '39 inches'
},
{
'name': 'Phillip Helm',
'guardians': 'Thomas Helm and Eva Jones',
'experience': 'YES',
'height': '44 inches'
}
]

我的做法是:

import random
from constants import PLAYERS
from constants import TEAMS
GREETING = 'BASKETBALL TEAM STATS TOOLn'
players = PLAYERS.copy()
teams = TEAMS.copy()
print(GREETING.upper())

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

max_players = len(players)/len(teams)
exp_players = []
nexp_players = []
panthers = []
bandits = []
warriors = []

squads = [panthers, bandits, warriors]
num_teams= len(squads)             

def balance_teams(players):
for player in players:
experience = player['experience']


if experience == 'YES':
exp_players.append(player)

else:
nexp_players.append(player)  


def balance_exp(exp_lists):
for num in range(len(exp_lists)):
squads[num % num_teams].append(exp_lists[num])

def dis_options():
print('Here are your Choices: n A) Display Team Stats n B) Quitnn')
while max_players > 0:
try:
activate = input('Enter an option: ')

if activate.lower() == "a" or activate.lower() == "b":

if activate.lower() == "a":
show_teams()

elif activate.lower() == "b":
print('Thank you, come back for more basketball stats!')
exit()
else:
raise ValueError

except ValueError as err:
print("nInvalid input.Please choose either A or Bn")


def show_teams():
print('nA)PanthersnnB)BanditsnnC)Warrirorsnn')
try:
team_sel= input('Enter an option: ')
if team_sel.lower() == "a" or team_sel.lower()=="b" or team_sel.lower() == "c":
if team_sel.lower() == "a":
team = "Panthers"
members = len(panthers)
exp_count = 0
height = []
for players in panthers:
if players['experience']== True:
exp_count += 1
height.append(players['height'])
nexp_count = (members - exp_count)
average_height = (round(sum(height)/members)) 

print('nTEAM: {} Statsn--------------------nTotal Players: {}nExperienced Players: {}nNon-experienced Players: {}nAverage Height: {} inchesnn'.format(team,members,exp_count,nexp_count, average_height))
print(pretty_data(*panthers, sep= ','))

elif team_sel.lower() == "b":
team = "Bandits"
members = len(bandits) 
exp_count = 0
height = []
for players in bandits:
if players['experience']== True:
exp_count += 1
height.append(players['height'])
nexp_count = (members - exp_count)
average_height = (round(sum(height)/members)) 

print('nTEAM: {} Statsn--------------------nTotal Players: {}nExperienced Players: {}nNon-experienced Players: {}nAverage Height: {} inchesnn'.format(team,members,exp_count,nexp_count, average_height))
print(pretty_data(*bandits, sep= ','))

elif team_sel.lower() == "c":
team = "Warriors"
members = len(warriors)
exp_count = 0
height = []
for players in warriors:
if players['experience']== True:
exp_count += 1
height.append(players['height'])
nexp_count = (members - exp_count)
average_height = (round(sum(height)/members)) 

print('nTEAM: {} Statsn--------------------nTotal Players: {}nExperienced Players: {}nNon-experienced Players: {}nAverage Height: {} inchesnn'.format(team,members,exp_count,nexp_count, average_height))
print(pretty_data(*warriors, sep= ','))

else:
raise ValueError

except ValueError as err:
print("nInvalid input.Please choose either A, B or Cn")     
def pretty_data(*team, sep= ','):
for player in team:
print(f"Name: {player['name']}nGuardians: {player['guardians']}nExperience: {player['experience']}nHeight: {player['height']}n")

if __name__ == '__main__':
def clean_data():
for player in players:
if player['experience'].lower() == 'yes':
player['experience'] = True
else:
player['experience'] = False

for player in players:
if player['height'] != int():
player['height'] = int(player['height'].split()[0])




balance_teams(players)
balance_exp(exp_players)
balance_exp(nexp_players)
clean_data()
dis_options()

接下来,我需要移除守护符之间的and,我使用:
for player in PLAYERS:
player['guardians'] = player['guardians'].split(' and ')

输出结果如下:

Name: Herschel Krustofski                                                                                                        
Guardians: ['Hyman Krustofski', 'Rachel Krustofski']                                                                             
Experience: True                                                                                                                 
Height: 45                                                                                                                       
                                                           
Name: Matt Gill                                                                                                                  
Guardians: ['Charles Gill', 'Sylvia Gill']                                                                                       
Experience: False                                                                                                                
Height: 40                                                                                                                       
                                                           
Name: Joe Kavalier                                                                                                               
Guardians: ['Sam Kavalier', 'Elaine Kavalier']                                                                                   
Experience: False                                                                                                                
Height: 39                                                                                                                       
                                                           
Name: Eva Gordon                                                                                                                 
Guardians: ['Wendy Martin', 'Mike Gordon']                                                                                       
Experience: False                                                                                                                
Height: 45                       

括号和引号被加回去。我尝试将.split添加到pretty_data函数,但它仍然包括' '和[]。有人能给我指点一下吗?

括号和引号是Python用来表示字符串(引号)和列表(括号)的符号。它们没有被加进去,你也不能把它们拿走。现在,如果您只是想打印它们而不看到括号,那么这很容易。

example = ['Hyman Krustofski', 'Rachel Krustofski'] 
print(f"Guardians: {example}")
print(f"Guardians: {', '.join(example)}")

这个收益率:

Guardians: ['Hyman Krustofski', 'Rachel Krustofski']
Guardians: Hyman Krustofski, Rachel Krustofski

简单替换:

player['guardians'] = player ['guardians'].replace(' and ',', ')

相关内容

  • 没有找到相关文章

最新更新