如何在 python 中附加或覆盖列表元素?
我目前正在尝试将我在 ruby 中使用的函数转换为 python,我的 ruby 代码如下所示:
def self.push_array_hash(key,selector,level,array)
(0..array.length).each do |i|
x = array[i]
selector[level] = i+1
if(x.is_a?(Array))
self.push_array_hash(key,selector,level+1,x)
end
self.push_datum("#{key}(#{selector.join(',')})", x)
end
end
我可以将此函数调用为:self.push_array_hash(key,Array.new,0,val)
而无需知道嵌套数组的维度。如果 selector[level]
尚不存在,代码 selector[level] = i+1
可以轻松处理将元素附加到数组,并更改 处的值级别
如果确实存在。
那是 ruby(只是为了让每个人都能理解我的目标),然后是 python。这是我翻译的代码:
def push_list_dict(self, key, selector, level, array):
for i, x in enumerate(array):
selector[level] = i+1
if isinstance(x, (list, set)):
if isinstance(value, set):
value = sorted(value)
self.push_list_dict(key,selector,level+1,x)
self.push_datum(key+"("+",".join(map(str, selector))+")",x)
我这样调用函数:self.push_array_dict(key,[],0,value)
,但是它在 selector[level] = i+1
处中断并给我错误:IndexError: list assignment index out of range
。有没有一种简单的方法可以将值附加到数组或重置值?谢谢,
约书亚
最佳答案
你可以使用:
selector[level:level+1] = [i+1]
如果 selector[level]
已经存在,这将替换该值。
如果它尚不存在,它会附加该值。
例如,
In [102]: selector = []
In [103]: selector[0:1] = [100]
In [104]: selector
Out[104]: [100]
In [105]: selector[0:1] = [200]
In [106]: selector
Out[106]: [200]
注意如果索引超出选择器
的长度会发生什么:
In [107]: selector[7:8] = [300]
In [108]: selector
Out[108]: [200, 300]
它不会在那个索引位置插入,它只是追加。
关于Python 附加或覆盖列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17538388/