我知道在Python中创建一个充满零的NxN数组的简单方法是:
[[0]*N for x in range(N)]
Run Code Online (Sandbox Code Playgroud)
但是,假设我想通过填充随机数来创建数组:
[[random.random()]*N for x in range(N)]
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为创建的每个随机数随后被复制N次,因此我的数组没有NxN唯一的随机数.
有没有办法在一行中执行此操作,而不使用for循环?
如何将对象属性的名称传递给函数?例如,我尝试过:
def foo(object, attribute):
output = str(object.attribute)
print(output)
class Fruit:
def __init__(self, color):
self.color = color
apple = Fruit("red")
foo(apple, color)
Run Code Online (Sandbox Code Playgroud)
但上述方法不起作用,因为Python认为,在中foo(apple, color),color指的是一个单一化的变量.