在Java ByteCode中,有一个名为“ istore_1”的操作码,它将堆栈的最高值存储到局部变量的索引1(列表)中。我正在尝试在python中复制它,但是如果您设置一个空列表的索引1,则它将设置索引0而不是索引1。我的想法是检查列表的第一个索引是否为空,以及是否已设置它喜欢“ emptyindex”之类的东西,但是经过一些研究,我没有找到检查索引是否为空的方法。我的问题是,即使尚未设置索引0,也如何将值存储到列表的索引1中,并将索引0设置为“ emptyindex”作为占位符。非常感谢:D
local_variables = []
stack = [1]
user = input("Enter instruction")
if user == "istore_1":
local_variables.insert(1, stack[0])
print(local_variables)
您可以使用函数来操作列表:
def expand(aList, index, value, empty=None):
l = len(aList)
if index >= l:
aList.extend([empty]*(index + 1 - l))
aList[index] = value
local_variables = []
expand(local_variables, 1, 'str')
print(local_variables)
输出:
[None, 'str']