python中列表的长度可以改变吗_在python中动态更改表的长度

这个示例展示了如何在Python中动态改变列表长度。通过使用`ph_dict`字典和`shapes`列表,创建了一个名为`DynamicTable`的类,该类包含一个可删除的表格,表格的列数根据`Shape`选择的值动态变化。当`Shape`的值改变时,`_Shape_changed`方法更新`shapes_name`列表,并调用`_updateShapeTable`方法重新构建表格,从而改变列表的长度。
摘要由CSDN通过智能技术生成

from traits.api import HasTraits, Instance, List, Str

from traitsui.api import Item, View, VGroup, EnumEditor,TableEditor, ObjectColumn

keys = ["key1", "key2", "key3"]

ph_dict={}

ph_dict["key1"] = ["A1","A2","A3"]

ph_dict["key2"] = ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"]

ph_dict["key3"] = ["C1", "C2","C3", "C4", "C5"]

shapes = ["square", "circle","inverted_triangle", "diamond", "dot", "cross", "plus",

"pixel"]

class ShapeTable(HasTraits):

pass

class DynamicTable(HasTraits):

Shape = Str

Shapedropdownlist = List(Str)

shapes_name = List(Str)

shape_table = List(Instance(ShapeTable))

shape_columns = [ObjectColumn(name="Name")]

shape_columns.append(ObjectColumn(name="Value"))

shape_table_editor=TableEditor(columns=shape_columns,

deletable = True,

sortable = False,

sort_model = False,

show_lines = True,

line_color = "black",

editable= False,

show_column_labels = False)

traits_view = View(VGroup(

Item('Shape',editor=EnumEditor(name='Shapedropdownlist',),),

Item( 'shape_table',editor=shape_table_editor,show_label=False,

width=0.3, padding=0)),

width=500, height=200, resizable=True,

title = "Dynamic table trait"

)

def __init__(self):

super(DynamicTable, self).__init__()

self.shapes_name = ph_dict[keys[1]]

self.shape_table_editor.columns = [ObjectColumn(name='name')]

for i in range(len(shapes)):

self.shape_table_editor.columns.append(ObjectColumn(name=shapes[i]))

self.Shapedropdownlist = keys

self.Shape = keys[2]

self._updateShapeTable()

return

def _Shape_changed(self, selectedValue):

self.pshape = selectedValue

self.shapes_name = ph_dict[self.pshape]

self._updateShapeTable()

def _updateShapeTable(self):

del(self.shape_table)

self.shape_table_editor.columns = [ObjectColumn(name='name')]

for i in range(len(self.shapes_name)):

print(i,len(self.shapes_name))

self.shape_table_editor.columns.append(ObjectColumn(name=shapes[i]))

data = ShapeTable()

data.name = "Name"

for i in range(len(self.shapes_name)):

print(i,len(self.shapes_name))

exec('data.'+shapes[i]+'="'+self.shapes_name[i]+'"')

self.shape_table.append(data)

data = ShapeTable()

data.name = "Shape"

for i in range(len(self.shapes_name)):

exec('data.'+shapes[i]+'="'+shapes[i]+'"')

self.shape_table.append(data)

if __name__ == "__main__":

f1 = DynamicTable()

f1.configure_traits()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值