以pythonic方式创建列表列表 [英] Creating lists of lists in a pythonic way

查看:81
本文介绍了以pythonic方式创建列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用列表列表在python中存储矩阵.我尝试按照以下步骤初始化2x3零矩阵.

I'm using a list of lists to store a matrix in python. I tried to initialise a 2x3 Zero matrix as follows.

mat=[[0]*2]*3

但是,当我更改矩阵中一项的值时,它会更改行中该条目的值,因为mat中每一行的ID都相同.例如,分配后

However, when I change the value of one of the items in the matrix, it changes the value of that entry in every row, since the id of each row in mat is the same. For example, after assigning

mat[0][0]=1

mat[[1, 0], [1, 0], [1, 0]].

我知道我可以使用如下循环创建零矩阵,

I know I can create the Zero matrix using a loop as follows,

mat=[[0]*2]
for i in range(1,3):
    mat.append([0]*2)

但是任何人都可以向我展示更多的pythonic方式吗?

but can anyone show me a more pythonic way?

推荐答案

使用列表理解:

>>> mat = [[0]*2 for x in xrange(3)]
>>> mat[0][0] = 1
>>> mat
[[1, 0], [0, 0], [0, 0]]

或者,作为功能:

def matrix(rows, cols):
    return [[0]*cols for x in xrange(rows)]

这篇关于以pythonic方式创建列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆