如何通过创建定义将列表中的多个项目分配给变量



我正试图创建一个定义,将列表中的对象分配给变量,但不幸的是,它不起作用:

当我尝试打印player_1时(如上一步(,它会给我一个

NameError

任何关于如何缩短或改进定义的建议或反馈都是受欢迎的。整个项目(一直到开始(都在进行https://github.com/ahmadkurdo/project---a

如果你有时间看一下,并给我一些反馈,我将不胜感激。

def assign_players(list_of_names):
if len(list_of_names) == 2:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
elif len(list_of_names) == 3:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
elif len(list_of_names) == 4:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
elif len(list_of_names) == 5:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
player_5 = list_of_names[4]
elif len(list_of_names) == 6:
player_1 = list_of_names[0]
player_2 = list_of_names[1]
player_3 = list_of_names[2]
player_4 = list_of_names[3]
player_5 = list_of_names[4]
player_6 = list_of_names[5]

number_of_players = int(input('How many players are playing?  '))
list_of_players = []
while number_of_players > 0:
name_player = input('What is your name  ')
list_of_players.append(name_player)
number_of_players = number_of_players - 1
assign_players(list_of_players)
print(player_1)

您的问题是变量的范围Scope的意思是:我的变量在哪里定义/可见,何时不再定义。

如果你在一个函数中定义了一个变量(就像你这样(,它只在这个函数中是已知的——一旦你离开这个函数,你就不能访问它。

变量未知,因此为NameError

然而,您可以return它,并通过将它分配给其他变量作为函数的返回。

你可以通过简化你的代码来解决你的特定问题(并去掉那些if语句(,如下所示:

number_of_players = int(input('How many players are playing?  '))
list_of_players = []
for _ in range(number_of_players):
list_of_players.append(input('What is your name  '))
player_1,player_2,player_3,player_4,player_5,player_6, *rest = list_of_players + [None]*5
print(list_of_players + [None] * 5) 
print(player_1)
print(player_2)
print(player_3)
print(player_4)
print(player_5)
print(player_6)
print(rest)

2+'jim'+'bob':的输出

['jim', 'bob', None, None, None, None, None] # filled up with [None] * 5
jim
bob
None
None
None
None
[]

代码的工作原理是将列表填充到所需的项目数量(对任何未输入的项目使用[None](,这样您就可以将列表再次分解为变量但是将它们留在列表中会容易得多:

for round in range(1,10):
for player in list_of_players:
print (player, "'s turn:")
# do something with this player

如果你想使用player_X变量,这有点困难,并且会导致大量重复代码,而且你仍然需要检查你的player_X是否已填充或None。。。

阅读更多关于:

  • 变量范围
  • 列表分解

作为函数:

def assign_players(p): 
return p + [None]*5
p1,p2,p3,p4,p5,p6,*rest = assign_players(list_of_players)

最新更新