【问题标题】:Coordinates Function that updates lists and stores them to be called坐标函数更新列表并存储它们以被调用
【发布时间】:2020-01-26 19:18:07
【问题描述】:

下面的函数存储两个数组“a”和“b”以用于线性回归图中。调用该函数以使用 coords(0, 0) 检索程序中其他地方的坐标,因此列表不会更新而只是返回。然后在向每个列表添加坐标时调用 coords(x, y)。但是,当它们被添加时,它们并没有被存储,因为当调用 coords(0, 0) 来检索更新的列表时,它只返回 'a' 和 'b'

x = [4,5] y = [9,10] coords(x, y) 然后应该返回 ([0,1,2,3,4,5], [5,6,7,8, 9,10])。我希望将这些存储起来,以便 coords(0, 0) 不添加任何其他内容但仍返回 ([0,1,2,3,4,5], [6,7,8,9,10])而不仅仅是“a”和“b”。我该怎么做呢?

def coords(x, y)
    a = [0,1,2,3]
    b = [5,6,7,8]
    xList = a
    yList = b
    if x == 0:
        return(xList, yList)
    else:
        xList = xList + x
        yList = yList + y
        return(xList, yList)

【问题讨论】:

  • 变量和函数名称应遵循lower_case_with_underscores 样式。您能否为此提供更多背景信息?为什么不能将数组存储在函数之外,甚至不能使用类?
  • 这能回答你的问题吗? Coordinates List that stores updated lists

标签: python python-3.x


【解决方案1】:

列表是可变的,您正在为每个函数调用创建ab。所以你需要让它们全球化。 试试这个:

a = [0,1,2,3]
b = [5,6,7,8]
def coords(x, y):
    if x == 0:
        return(a, b)
    else:
        a.extend(x)
        b.extend(y) # Faster and recommended way of adding elements to a #list.
        return(a, b)

【讨论】:

  • .extend() 不返回None?我不确定@tomparko 是如何让它发挥作用的......
  • 是的,删除 globala =b = 修复它。你真的运行过这个吗?
  • 谢谢@amc 我很着急,没看到。再次感谢。
猜你喜欢
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
相关资源
最近更新 更多