【问题标题】:Python: Append Dictionary new elementPython:追加字典新元素
【发布时间】:2015-02-04 19:20:46
【问题描述】:

转换 PHP 代码:

$this->plane[$slice_id][$f][] = array('x' => $y, 'y' => $z);

到蟒蛇:

self.plane = {};

self.plane[slice_id][f][] = {'x' : y, 'y' : z};

不起作用。

1) self.plane[slice_id][f] -> 尚未初始化。仅在必要时创建此元素。

2) [] -> 将元素推送到数组

3) Python 字典通常不是多维的

【问题讨论】:

标签: python arrays dictionary multidimensional-array


【解决方案1】:

这样试试

self.plane[slice_id][f] = [] 
self.plane[slice_id][f].append( {'x' : y, 'y' : z} )

append() 方法将传递的obj 附加到现有列表中。

self.plane[slice_id][f][] = {'x' : y, 'y' : z}; 不是 python 的有效语法

演示

>>> new_list = []
>>> new_list[] = 'test'
  File "<stdin>", line 1
    new_list[] = 'test'
             ^
SyntaxError: invalid syntax

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2015-12-03
    • 2017-05-06
    相关资源
    最近更新 更多