列表未附加我想为使用for循环的两个用户追加电路板列表我该怎么办
from random import randint
user1 = {
"name":input("Enter your name"),
"board":[]
}
user2 = {
"name":input("Enter your name"),
"board":[]
}
users = [user1, user2]
def set_board(users):
for x in range(5):
users["board"].append(x)
def print_board(users):
for row in users["board"]:
print(" ".join(row))
print("Let's start")
print(print_board(user1))
print(print_board(user2))
答案 0 :(得分:2)
set_board
print_board
不返回任何内容,因此您无法打印返回值这是一个工作版本:
from random import randint
user1 = {
"name":input("Enter your name"),
"board":[]
}
user2 = {
"name":input("Enter your name"),
"board":[]
}
users = [user1, user2] # Actually this is not used anymore
def set_board(user):
for x in range(5):
user["board"].append(x)
def print_board(user):
print(' '.join(str(user["board"])))
print("Let's start")
set_board(user1)
set_board(user2)
print_board(user1)
print_board(user2)
答案 1 :(得分:0)
您永远不会调用set_board()函数。此外,print(print_board(user1))语句不会打印任何内容,因为print_board()=>中没有返回值。只需调用print_board(user1)
答案 2 :(得分:0)
正如其他人指出的那样,你实际上从来没有打电话给'set_board',但如果你这样做就会失败。当您附加整数时,您将附加到用户[' board'],而不是附加到用户1 [' board']或user2 [' board']。实际上,当您尝试进行该分配时,python应该抛出TypeError。
TypeError:list indices必须是整数,而不是str
类似的东西:
def set_board(users):
for my_user in users:
for x in range(5):
my_user.append(x)
会将整数附加到每个用户(user1和user2)。 Ť