你如何替代追加或覆蓋python中的列表元素?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]
尚不存在,並且在level
存在的情況下更改該值,代碼selector[level] = i+1
可輕鬆處理將元素附加到數組。
這是紅寶石(只給予所以每個人都可以理解我的目標),到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
。是否有一種簡單的方法將數值附加到數組或重置值?謝謝,
約書亞
相反,你可以解釋一下你正在試圖解決這個問題,有一個例子,你可能會得到更好的Python的解決方案 –