Python 如何通过创建定义将列表中的多个项分配给变量
我正在尝试创建一个定义,将列表中的对象分配给变量,但不幸的是,它不起作用: 当我尝试打印Python 如何通过创建定义将列表中的多个项分配给变量,python,python-3.x,variables,Python,Python 3.x,Variables,我正在尝试创建一个定义,将列表中的对象分配给变量,但不幸的是,它不起作用: 当我尝试打印player_1(如上一步)时,它会给我一个 NameError 任何关于如何使定义更短或更好的建议或反馈都是受欢迎的。整个项目(直到开始)正在进行中 如果你有时间,看看它,给我一些反馈,将不胜感激 def assign_players(list_of_names): if len(list_of_names) == 2: player_1 = list_of_names[0]
player_1
(如上一步)时,它会给我一个
NameError
任何关于如何使定义更短或更好的建议或反馈都是受欢迎的。整个项目(直到开始)正在进行中
如果你有时间,看看它,给我一些反馈,将不胜感激
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)
您的问题是变量的范围范围表示:我的变量在哪里定义/可见,何时不再定义 如果您在函数中定义变量(就像您所做的那样),它只在该函数中被知道-一旦您离开该函数,您就无法访问它 变量未知-因此
namererror
但是,您可以返回它,并将它指定给其他变量作为函数的返回
您可以通过如下方式简化代码来解决特定问题(并摆脱那些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是否已填充
阅读更多关于:
作为功能:
def assign_players(p):
return p + [None]*5
p1,p2,p3,p4,p5,p6,*rest = assign_players(list_of_players)
您已经在列表中列出了您的项目,为什么希望它们污染您的范围?先生,非常感谢您的帮助,并感谢您的反馈!