【问题标题】:Python: for loop does not perceive updated listPython:for循环不感知更新的列表
【发布时间】:2019-12-08 16:29:34
【问题描述】:

函数 point() 中的 for 循环不考虑在 game() 函数中已更新点列表。我该如何解决这个问题,所以结果是带有更新值的 names_points 列表。

names = ["peter", "sofia", "reinhard", "leo"]

points = [10] * (len(list))

def point(points):
    for i in range(0, len(points)):
        names_points = [name + " has " + str(points[i]) + " points." for name in names]
    return names_points


def game():
    x = points[0] - 1
    points.remove(points[0])
    points.insert(0, x)
    return point(points)

print(game())

【问题讨论】:

  • 请注意,您在循环的每次迭代中都会覆盖 names_points 的值。我相信您正在寻找的是appendnames_points 列表。所以像names_points.append([name + " has " +...])
  • 您还可以在点函数中使用点作为参数。这意味着,您不会改变全局点变量,而是改变全局变量的局部变量。
  • 您遇到错误了吗?它是什么?您希望看到什么?
  • @TheFool。但他正在传递它
  • 是的,没错。对不起

标签: python python-3.x list loops


【解决方案1】:

我相信您正在尝试返回一个字符串列表,其中描述了每个玩家的姓名以及他们目前拥有的分数。

您的代码的问题不是它没有感知到更新的列表,而是它在迭代points 列表的 for 循环的每次迭代中创建一个新列表。此列表用一个新列表覆盖names_point,该列表由所有玩家的姓名和当前points[i] 的分数组成。

要解决第一个问题,您可以像这样使用zip 修复您的列表理解:

names_point = [name + " has " + str(player_points) + " points." for name, player_points in zip(names, points)] 

因此也消除了第二个问题。如果您不希望使用列表推导,您可以改用 points[i]append 以下列方式将字符串聚合到 names_point 中:

names_points = []
for i in range(len(points)):
        names_points.append(names[i] + " has " + str(points[i]) + " points.")

【讨论】:

    猜你喜欢
    • 2018-10-29
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多