提问者:小点点

是否有可能使用“for循环”访问不同的列表?


我尝试使用for循环对不同的列表进行更改,如下所示:

# Variable that indicates who scored a goal. Can either take value a or b.
goal = "a"

# Initiate points counter
points_a = [0]
points_b = [0]

players = ["a", "b"]

for x in players:
    if goal == x:
        points_x[0] += 1

print(points_a)

我想根据goal取值a还是b来更新“points counter”,但是我正在努力找到一种方法来告诉Python我正在尝试访问循环中的列表。 在本例中,目标设置为“a”,我希望的输出是“[1]”。 目前,我刚刚得到错误“nameerror:name'points_x'不定义”。 在Python中有没有办法做到这一点?

感谢任何提示!

曼努埃尔


共2个答案

匿名用户

您可以使用普通字典来代替两个变量:

# Variable that indicates who scored a goal. Can either take value a or b.
goal = "a"

# Initiate points counter
player_points = { "a": 0, "b": 0 }

# no need for loop
player_points[goal] += 1

print(player_points["a"])

匿名用户

基本上,你想要的是一个球员和他们的点数之间的映射。 您可以通过字典来完成此操作:

goal = "a"
player_dict = {
    "a":[0],
    "b":[0]
}

player_dict[goal][0] += 1 

我也不知道为什么要使用一个列表而不是一个整数来存储点数。