gpt4 book ai didi

python - 在 python 中。当字典位于类中时,如何让用户更改字典值?

转载 作者:行者123 更新时间:2023-12-01 06:08:31 25 4
gpt4 key购买 nike

所以我有一个类似的问题,并在另一个线程中得到了回答。

How do I update a dictionary value having the user choose the key to update and then the new value, in Python?

基本上,如何通过 raw_input 更改嵌套字典值。我使用了该解决方案并且效果很好,但我想使用类来编写程序。因此,我创建了一个类,其中包含使用基本相同的代码编辑字典的方法,但是当我尝试在类方法中运行它时,它现在给了我一个“关键错误”。

因此,在主函数中,上述链接问题中的解决方案效果很好。但在类方法中:

class team: # create a class where each team will be an instance
def __init__(self, name):
self.name = name #name of team will be passed from main
self.list_of_players = [] # create a list of the players
self.position1 = {} # create a dictionary for each of the positions on that team
self.position2 = {}
self.roster = [self.position1, self.position2]

def addplayer(self, player_name): # the name of the player is passed to this method from main
print 'add stats' # fill out the appropriate stats through raw_input
stat1 = raw_input('stat1: ')
stat2 = raw_input('stat2: ')
pos = raw_input('POS: ')
vars()[player_name] = {'stat1' : stat1, 'stat2' : stat2, 'POS' : pos} #create a dictionary
# for the player where all his stats are kept
player = {player_name : vars()[player_name]} # create a dictionary that will show the
# player's name as a string and his stats which are held in the dictionary named after him
self.list_of_players.append(player) # append the new player to the list of players
if pos == 'p1': # add the player and his stats to the appropriate position on the team
self.position1[player_name] = player
elif pos == 'p2':
self.position2[player_name] = player
else:
pass

def editplayer(self, player_name): # player's name is passed to the edit function from main
print self.list_of_players # player's name shows up in the list of players for the team
edit_stat = raw_input('which stat? ') # choose which stat(key) to edit via raw input
new_value = raw_input('new value: ') # choose the new value to apply to the chosen key
vars()[player_name][edit_stat] = new_value # here is where it gives a key error! this worked
#in fact even trying to call and print the players name gives the key error.
#player = vars()[player_name]
#print player

def main(): # the main function
loop1 = 0 # creating a loop so one can come back and edit the teams after creating them
list_of_teams = [] # initializing list of teams
while loop1 < 1:
print list_of_teams # show the user what teams are available to choose from
team_option = raw_input('new team or old: ') # create a new team or work with an old one
if team_option == 'new':
team_name = raw_input('team name? ') # get the team name from raw_input
vars()[team_name] = team(team_name) #create an instance of this team name
list_of_teams.append(team_name) # add the team to the list
else:
team_name = raw_input('which team? ') # choose which existing team to work with
player_choice = raw_input('new player or old? ') # choose to create or edit existing player
player_name = raw_input('player_name? ') # choose which player from raw_input
if player_choice == 'new':
vars()[team_name].addplayer(player_name) # give player_name to addplayer method
print vars()[team_name].list_of_players # shows the new player in the appropriate
# instance's roster. This method seems to be working fine
else:
vars()[team_name].editplayer(player_name) # gives the player's name to the editplayer
# method for the appropriate instance. But the player name just raises a key error in
# edit player method. I am baffled.
print vars()[team_name].list_of_players
if __name__ == '__main__':
main()

当这只是一个长函数时,它可以工作,但看起来像是一场灾难。试图学习更好的 OOP 实践,但我不知道如何通过玩家的名字调用该字典来更改值。在过去的几天里,我一直在审查有关类和字典的教程和问题,但显然我误解了变量如何从函数传递到方法的一些内容。

事实上,它甚至不会将字典 vars()[player_name] 分配给要打印的 var,这意味着它无法将其识别为我认为在 addplayer 方法中创建的字典。但事实上,它仍然在玩家列表中列出该字典,这意味着它存在于该实例中。那么,当我尝试在 editplayer 方法中解决它时,为什么它无法识别它呢?如何调用在一种方法中创建的嵌入字典,以在第二种方法中更改该字典中的值?

卡尔指出了需要澄清的好点:这就是我想要的属性。

self.name-我想要为每个创建的团队一个实例

self.list ofplayers - 每个团队都应该有自己的球员列表,这些列表是保存该人统计数据的字典。所以 team1 应该有自己的列表。 team2 不同的列表等

self.position1/2 - 每支球队的球员将被归档在他们的不同位置字典中。所以球员乔·蒙塔纳的统计字典可以在该球队的四分卫字典中找到

self.roster - 应该是按职位分组的球队名单。因此,调用 print team1.roster 应该打印按位置分组的球员

最佳答案

1) vars()函数内局部变量的字典。

当您使用 Python 中的方法时,调用该方法的对象的内容不是局部变量。这就是为什么你必须有一个 self 参数。

如果您想按姓名查找玩家,请这样做。没有玩家列表,而是玩家字典。

2) vars() 是你几乎不应该使用的东西。使用它可以将字符串假装为变量名。您不需要为您在这里所做的任何事情执行此操作。事实上,在大多数使用变量的地方根本不需要变量。您需要了解的不仅仅是面向对象。

以这部分为例:

vars()[team_name] = team(team_name)
list_of_teams.append(team_name)

不要再尝试在 vars() 中按名称记住团队,而是按名称查找团队。制定团队指令而不是列表。要获取团队名称,您只需打印字典的键即可。

简单总比复杂好。动态创建变量很复杂。使用字典很简单。

<小时/>

我讨厌用勺子喂这么多代码,但这似乎是这次获得想法的唯一方法(我并没有真正说出上面的所有内容):

# Just like we want a class to represent teams, since those are "a thing" in our
# program, we want one for each player as well.

class player(object):
__slots__ = ['name', 'stats', 'pos']
def __init__(self, name, stats, pos):
self.name = name
self.stats = stats
self.pos = pos


# Asking the user for information to create an object is not the responsibility of
# that class. We should use external functions for this.
def create_player(name):
print 'add stats' # fill out the appropriate stats through raw_input
stat1 = raw_input('stat1: ')
stat2 = raw_input('stat2: ')
pos = raw_input('POS: ')
# Now we create and return the 'player' object.
return player(name, {'stat1': stat1, 'stat2': stat2}, pos)


class team(object):
__slots__ = ['name_to_player', 'position_to_player']
def __init__(self):
# We don't make any lists, just dicts, because we want to use them primarily
# for lookup. Notice how I've named the attributes. In particular, I **don't**
# talk about type names. That's just an implementation detail. What we care about
# is how they work: you put a name in, get a player out.
self.name_to_player = {}
self.position_to_player = {}

# Again, we don't ask the questions here; this just actually adds the player.
def add_player(self, player):
self.name_to_player[player.name] = player
self.position_to_player[player.pos] = player

# Again, we don't ask the questions here; this just does the actual edit.
def edit_player(self, name, stat, new_value):
self.name_to_player[name].stats[stat] = new_value


def main(): # the main function
teams = {} # dict from team name to team object.
while True:
print teams.keys()
# Your human interface was needlessly awkward here; you know from the supplied name
# whether it's a new team or an old one, because it will or won't be in your
# existing set of teams. Similarly for players.
team_name = raw_input('team name? ')
if team_name not in teams.keys():
teams[team_name] = team() # create a new team
else: # edit an existing one
team = teams[team_name]
player_name = raw_input('player name? ')
if player_name in team.name_to_player.keys(): # edit an existing player
stat = raw_input("stat? ")
value = raw_input("value? ")
team.edit_player(player_name, stat, value)
else: # add a new player
team.add_player(create_player(player_name))

if __name__ == '__main__':
main()

这个仍然并没有把所有事情都做“正确”,但它应该给你现在足够多的思考。

关于python - 在 python 中。当字典位于类中时,如何让用户更改字典值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6906132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com