我有一个这样的清单:
my_array= ["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
我想做的是:
define('device','xyz')
define('asd','10')
define('pdf','6')
define('dsa','1')
define('pqa','2')
define('dga','12')
我接近的方式是:
i=0
while i < len(my_array):
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
elif my_array[i][0]=="+":
print("'",my_array[i][1],"'","'",my_array[i][3],"'")
if my_array[i][4]=="\D":
print("'",my_array[i][4],"'","'",my_array[i][6],"'")
elif my_array[i][7]=="\D":
print("'",my_array[i][7],"'","'",my_array[i][9],"'")
i=i+1
但是这样做,我得到索引错误。我知道问题出在哪里,但我不能用我非常糟糕的编程大脑来修复它。有人可以帮我吗?
答案 0 :(得分:1)
首先回顾问题
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
因为my_array
中的最后一个元素是['*']
而且它没有其他元素,并且您正在尝试访问my_array['*'][1]
并且它给出索引错误。
您必须删除该元素或添加满足元素索引要求的成员。
答案 1 :(得分:0)
对索引进行硬编码是一个肯定的迹象,表明你做错了 - my_array
中的项目具有可变长度,因此你的一些索引不可避免地会失败。我想你想要的是:
for command in my_array:
if command[0] in ("*", "+"):
for start in range(1, len(command), 3):
assignment = command[start:start+3]
if assignment[1] in ("=", ":"):
print assignment[0], assignment[2]
但值得注意的是,您似乎正在尝试编写文件解析器。虽然此代码解决了这个特定问题,但可能会改进您的整体方法。
答案 2 :(得分:0)
假设您列表中的每个键都附加了一个值(例如,彼此之后没有两个星号),您可以进行一些简化:
我们将第一个值读作新dict的键,第二个值作为值。 通过新整理的词典(d),您可以继续轻松工作,例如在for循环中:
array=["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
d = {}
for list in array:
new_key = None
for item in list:
if item in ['*',':','+','=']: continue
if new_key == None:
new_key = item
else:
d[new_key] = item
new_key = None
for key in d:
define(key,d[key])