创建和使用列表列表列表:在Python中 [英] Creating and working with list of lists of lists: in Python

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

问题描述

我是Python的新手,出于某些需求,我试图弄清楚如何使用列表列表.

I'm new with Python and for some needs I am trying to figure out how to work with list of lists of lists.

这是我在做什么:

segment_coef = [[list()]*4]*17 
print segment_coef
segment_coef[0][0].append(1)
segment_coef[1][0].append(2)
segment_coef[2][0].append(3)
print segment_coef

在第一个print之后,我有:

[ [ [],[],[],[] ] , ... 14 more time ... , [ [],[],[],[] ] ]


在这三个append命令之后,我希望有以下内容:


After these three append commands I'd like to have smth like:

[ [ [1],[],[],[] ] , [ [2],[],[],[] ], [ [3],[],[],[] ] ]

但是我有:

[ [ [1,2,3],[1,2,3],[1,2,3],[1,2,3] ] , [ [1,2,3],[1,2,3],[1,2,3],[1,2,3] ], ... up to the end ]

我在做什么错了?

推荐答案

有几种方法可以创建一个由17个列表组成的列表,每个列表包含4个子列表

There are a couple of ways to create a list of 17 lists of 4 sublists each

最短的是

[[list() for i in range(4)] for j in range(17)] 

如果这样做,您的附件将按您希望的那样工作

If you do this, your appends will work as you want them to

如果您熟悉不具备列表理解功能的C或Java之类的语言,则对您来说可能更熟悉:

If you're familiar with languages like C or Java that don't have list comprehensions, this way might look more familiar to you:

l = []
for j in range (17):
  k = []
  for i in range (4):
    k.append(list())
  l.append (k)

这也是可以接受的,但是对于许多python头来说,列表理解是更可取的. list comp应该在性能方面至少与理解一样好.

This is also acceptable, but for many python heads, the list comprehension is preferable. The list comp should be performance-wise at least as good as the comprehension.

这篇关于创建和使用列表列表列表:在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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