Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何使数组中的引用元素自动更新?_Python - Fatal编程技术网

Python:如何使数组中的引用元素自动更新?

Python:如何使数组中的引用元素自动更新?,python,Python,我做了一个类似这样的课程: import numpy.random as rand class Dice: def __init__(self): self.x=0 def roll(self): self.x=int(rand.randint(1,7,1)) print(self.x) import numpy.random as rand class Dice: def __init__(self):

我做了一个类似这样的课程:

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        print(self.x)
import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
        self.dicelist = []
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        self.dicelist.append(self.x)
        return self.dicelist
A=Dice()
A.roll()
A.roll()
A.roll()
print(A.roll())
#[3, 1, 4, 2]
现在,我想掷两个骰子,并用结果制作一个数组

A=Dice()
B=Dice()
aaa=[A.x, B.x]
print(aaa)

A.roll()
B.roll()
print(aaa)
结果如下:

[0, 0]
2
4
[0, 0]

我希望这段代码的作用是使数组在内部的数字发生变化时自动更新。我知道我可以通过创建另一个函数来实现这一点,但是有没有其他方法可以使这项工作更优雅?

在您当前的代码中,一旦执行该行,aaa中的值是固定的。你应该保存骰子的实例。repr方法用于将类内的信息传递出去

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        print(self.x)
    def __repr__(self):
        return str(self.x)
A=Dice()
B=Dice()
aaa=[A, B]
print(aaa)

A.roll()
B.roll()
print(aaa)

结果:

[0, 0]
4
6
[4, 6]

您可以在列表中跟踪您的卷,并添加如下新卷:

import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        print(self.x)
import numpy.random as rand
class Dice:
    def __init__(self):
        self.x=0
        self.dicelist = []
    def roll(self):
        self.x=int(rand.randint(1,7,1))
        self.dicelist.append(self.x)
        return self.dicelist
A=Dice()
A.roll()
A.roll()
A.roll()
print(A.roll())
#[3, 1, 4, 2]

不能对int对象进行变异,但可以对骰子对象进行变异。换句话说,列表中的数字永远不会改变。把你的骰子对象放在列表中而不是数组中,而把int对象放在一边,到底为什么要把numpy放在这里面呢?只需使用导入随机数Yeap,这是真的✅