Python 是否有可能使用;for loop";要访问不同的列表?

Python 是否有可能使用;for loop";要访问不同的列表?,python,for-loop,Python,For Loop,我尝试使用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

我尝试使用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中有没有实现这一点的方法

谢谢你的提示


Manuel

您可以使用普通字典而不是两个变量:

# 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"])

您可以使用普通字典而不是两个变量:

# 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 

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

基本上,你想要的是一个玩家和一个玩家之间的映射。 您可以通过字典执行此操作:

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

player_dict[goal][0] += 1 

我也不清楚为什么要使用列表而不是单个整数来存储点。

点x
确实没有在代码中定义。Python不会基于
x
为您神奇地将
points\ux
转换为
points\uA
points\uB
——这不是代码工作的方式使用
dict
将点存储为
dict值
,将播放器存储为
dict键
players={“a”:0,“b”:0};玩家[goal]+=1
积分\u x
确实没有在您的代码中定义。Python不会基于
x
为您神奇地将
points\ux
转换为
points\uA
points\uB
——这不是代码工作的方式使用
dict
将点存储为
dict值
,将播放器存储为
dict键
players={“a”:0,“b”:0};玩家[goal]+=1
。为什么要列出这些值?谢谢,非常有用。我使用列表是因为我最熟悉它们,但你是对的。使用一个简单的整数就可以了。为什么会有值列表?谢谢,非常有用。我使用列表是因为我最熟悉它们,但你是对的。使用一个简单的整数就可以了。