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

时间:2018-12-01 12:19:02

标签: python python-3.x variables

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

当我尝试打印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)

1 个答案:

答案 0 :(得分:0)

您的问题是变量的作用域 范围 的意思是:我的变量在哪里定义/可见,什么时候不再定义。

如果您在函数内部定义了变量(就像您一样),则仅在该函数内部知道它-离开函数后就无法访问它。

变量是未知的-因此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是否已填充或无...

详细了解:

功能:

def assign_players(p): 
    return p + [None]*5

p1,p2,p3,p4,p5,p6,*rest = assign_players(list_of_players)