【问题标题】:Why can't I change the values of a list in the class using a method?为什么我不能使用方法更改类中列表的值?
【发布时间】:2020-10-24 21:57:12
【问题描述】:

我正在尝试使用 python 实现简单的快速查找算法。这是我第一次在 Python 中使用 OOP。以下是我采取的步骤:

  1. 使用 init 方法创建类,使其接受 N 否。列表的元素数量 - “id”,我将 0 - N-1 个元素附加到列表中。

    class QuickFindUF:
       def __init__(self, N):
       self.id = []
       for i in range(N):
           self.id.append(i)
    
  2. 我创建了一个接受参数的联合方法:p & q(这些是我要连接的值),然后更改列表值,以便将具有 pid 的列表项更改为 qid。

    def union(self,p, q):
        pid = self.id[p]
        qid = self.id[q]
        for i in range(len(self.id)):
        if self.id[i] == pid:  # This part is getting ignored, I think.
            self.id[i] == qid
    
  3. 我创建 get_id 方法来查看 id 的变化。

    def get_id(self):
        return self.id
    
  4. 现在在主要部分中,我这样做是为了查看结果:

    if __name__ == "__main__":

    qf = QuickFindUF(5)
    print(qf.get_id())
    qf.union(0, 3)
    print(qf.get_id())   
    

调用 union 方法后,我应该会看到更新后的 id[],但 id 没有改变。
预期输出:[0, 1, 2, 3, 4] [3, 1, 2, 3, 4]
实际输出:[0, 1, 2, 3, 4] [0, 1, 2, 3, 4]

我尝试在不使用 union 方法中的“if”语句的情况下手动更改 id 的一些值,结果很好,例如: id[0] = 'a' 结果很好:输出是: [0, 1, 2, 3, 4] ['a', 1, 2, 3, 4]

如果我使用带有 if 语句的 for 循环来更改列表的值,为什么 union 方法不起作用?

我还尝试像这样在 union() 中返回 id[]:
def union(self,p, q):

```pid = self.id[p]
    qid = self.id[q]
    for i in range(len(self.id)):
    if self.id[i] == pid:  # This part is getting ignored, I think.
        self.id[i] == qid```

但是当我打印时得到相同的输出(qf.union())

【问题讨论】:

  • 错字。 self.id[i] == qid 应该使用=,而不是==

标签: python list algorithm oop mutation


【解决方案1】:

试试这个

def union(self,p, q):
    pid = self.id[p]
    qid = self.id[q]
    for i in range(len(self.id)):
        if self.id[i] == pid:  # This part is getting ignored, I think.
            self.id[i] = qid

【讨论】:

  • 对不起,我刚刚看到,使用 == 而不是 =。我要删除刚才的问题。
【解决方案2】:

我建议使用 numpy:

import numpy as np

class QuickFindUF:

   def __init__(self, N):
       self.id = np.arange(N)  # Quicker with numpy

   def union(self, p, q):
       pid = self.id[p]
       qid = self.id[q]
       
       # Use powerful np.where
       self.id = np.where(self.id == pid, # Where self.id = pid,
                          qid, # changes it to qid,
                          self.id)  # the rest of the array remains unchanged

   def get_id(self):
       return self.id


if __name__ == "__main__":
    qf = QuickFindUF(5)
    print(qf.get_id())
    qf.union(0, 3)
    print(qf.get_id())

如果我正确理解了您的问题,它应该可以正常工作。否则调整 np.where() 的参数。

祝你好运!

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 2013-06-10
    • 2012-02-10
    相关资源
    最近更新 更多