具有固定数量的元素的python列表 [英] python list with fixed number of elements

查看:104
本文介绍了具有固定数量的元素的python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Python中创建一个大小为6的元组的固定大小列表.请注意,在下面的代码中,我总是在重新初始化外部for循环中的值,以重置先前创建的列表,该列表已添加到globalList中.这是一个代码段:

I want to create a fixed size list of size 6 of tuples in Python. Note that in the code below i am always re-initializing the values in the outer for loop in order to reset the previously created list which was already added to globalList. Here is a snippet:

for i,j in dictCaseId.iteritems():
    listItems=[None]*6
    for x,y in j:
        if x=='cond':
            tuppo = y
            listItems.insert(0,tuppo)
        if x=='act':
            tuppo = y
            listItems.insert(1,tuppo)
        if x=='correc':
            tuppo = y
            listItems.insert(2,tuppo)
            ...
            ...
    globalList.append(listItems)

但是当我尝试运行上面的代码(上面仅显示了代码段)时,它会增加列表的大小.我的意思是,添加了东西,但我还看到列表包含更多数量的元素.我不希望我的列表大小增加,并且我的列表是6个元组的列表.

But when I try to run the above (snippet only shown above) it increases the list size. I mean, stuff gets added but I also see the list contains more number of elements. I dont want my list size to increase and my list is a list of 6 tuples.

例如:

Initially: [None,None,None,None,None,None]
What I desire: [Mark,None,Jon,None,None,None]
What I get: [Mark,None,Jon,None,None,None,None,None]

推荐答案

而不是插入,您应该分配这些值. list.insert在传递给它的索引处插入一个新元素,因此列表长度在每次插入操作后增加1. 另一方面,赋值会修改特定索引处的值,因此长度保持不变.

Instead of inserting you should assign those values. list.insert inserts a new element at the index passed to it, so length of list increases by 1 after each insert operation. On the other hand assignment modifies the value at a particular index, so length remains constant.

for i,j in dictCaseId.iteritems():
    listItems=[None]*6
    for x,y in j:
        if x=='cond':
            tuppo = y
            listItems[0]=tuppo
        if x=='act':
            tuppo = y
            listItems[1]=tuppo
        if x=='correc':
            tuppo = y
            listItems[2]=tuppo

示例:

>>> lis = [None]*6
>>> lis[1] = "foo"   #change the 2nd element
>>> lis[4] = "bar"   #change the fifth element
>>> lis
[None, 'foo', None, None, 'bar', None]

更新:

>>> lis = [[] for _ in xrange(6)] # don't use  [[]]*6
>>> lis[1].append("foo")
>>> lis[4].append("bar")
>>> lis[1].append("py")
>>> lis
[[], ['foo', 'py'], [], [], ['bar'], []]

这篇关于具有固定数量的元素的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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