Python-动态嵌套列表 [英] Python - Dynamic Nested List

查看:163
本文介绍了Python-动态嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图根据宽度和高度在Python中生成一个嵌套列表.这是我到目前为止的内容:

So I'm trying to generate a nested list in Python based on a width and a height. This is what I have so far:

    width = 4
    height = 5
    row = [None]*width
    map = [row]*height

现在,这显然是不对的.打印后看起来不错:

Now, this obviously isn't quite right. When printed it looks fine:

[[None, None, None, None],
 [None, None, None, None],
 [None, None, None, None],
 [None, None, None, None],
 [None, None, None, None]]

但是尝试将值分配给这样的位置:

But attempting to assign a value to a position like so:

map[2][3] = 'foo'

我得到:

[[None, None, None, 'foo'],
 [None, None, None, 'foo'],
 [None, None, None, 'foo'],
 [None, None, None, 'foo'],
 [None, None, None, 'foo']]

很明显,发生这种情况是因为每个子列表实际上只是在引用同一对象,行,因此更改一个对象将全部更改.所以这是我最近的!

Clearly this happens because each sublist is really just referencing the same object, row, so changing one, changes them all. So this is closest I've got!

如何动态生成嵌套列表?谢谢!

How can I dynamically generate a nested list? Thanks!

推荐答案

当您执行[row]*height时,最终会在每一行中使用相同的列表对象. row数组引用在每一行中重复,这意味着每一行实际上都指向同一列表对象.因此,修改一行实际上会修改所有行.

When you do [row]*height you end up with the same list object in each row. The row array reference is repeated in each row which means each row is actually pointing to the same list object. Hence modifying one row actually modifies all rows.

看看为您打印 id() 时会发生什么每一行.他们都是一样的!

Take a look at what happens when you print the id() for each row. They're all the same!

>>> grid = [[None] * width] * height
>>> [id(row) for row in grid]
[148014860, 148014860, 148014860, 148014860, 148014860]

您可以使用列表理解功能,使python为每一行生成单独但相同的列表.使用[rowexpr for i in xrange(height)]时,rowexpr将每行评估一次.然后,诀窍是使用一个表达式,该表达式每次被评估时都会产生一个唯一列表.

You can get python to generate separate-but-identical lists for each row by using a list comprehension. When you use [rowexpr for i in xrange(height)] then rowexpr will be evaluated once per row. The trick then is to use an expression that will result in a unique list each time it is evaluated.

如果您看到它,它将更有意义:

This'll make more sense if you see it in action:

>>> grid = [[None] * width for i in xrange(height)]
>>> grid[2][3] = 'foo'
>>> grid
[[None, None, None, None],
 [None, None, None, None],
 [None, None, None, 'foo'],
 [None, None, None, None],
 [None, None, None, None]]

每次评估[None] * width时,都会生成一个新列表.

Each time [None] * width is evaluated it generates a new list.

>>> [id(row) for row in grid]
[148016172, 148015212, 148016236, 148016108, 148016332]

这篇关于Python-动态嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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