2016-06-08 66 views
-1

谁能帮我解决以下两个问题:循环错误。和空变量

1)考虑下面的代码:如果我打印Listposblocks_COG1它会返回一个空变量。我究竟做错了什么。请注意,'结果'变量要大得多,但我只复制了一小段。 2)考虑下面的代码:如果我打印Listposblocks_COG2或Listposblocks_COG3 Ireceive错误消息:NameError:name'Listposblocks_COG2'未定义。我在这里做错了什么?

谢谢。

#Only part of the table, but it would take too much space. 
    results = [[336350.0, 7089650.0, -7.0, 0.1665, 1.5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [336350.0, 7089650.0, -5.0, 0.1542, 1.5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [336350.0, 7089650.0, -3.0, 0.2259, 1.5, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [336350.0, 7089650.0, -1.0, 0.2753, 1.5, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]] 

Start_index_nulzero = int(Length_Data_BM_Sorted) 


if Start_index_nulzero == 5: 
    Listposblocks_COG1 = [] 
    for i in results: 
     if results[5] == 1: 
      Listposblocks_COG1.append(i) 


    if type(results[6]) == int: 
     Listposblocks_COG2 = [] 
     for i in results: 
      if results[6] == 1: 
       Listposblocks_COG2.append(i) 


    if type(results[7]) == int: 
     Listposblocks_COG3 = [] 
     for i in results: 
      if results[7] == 1: 
       Listposblocks_COG3.append(i) 

print Listposblocks_COG1 
print Listposblocks_COG2 
print Listposblocks_COG3 
+0

代码中没有打印声明 – Railslide

+0

在我的真实脚本中有。然后它返回并清空Listposblocks_COG1,并为COG2和COG3提供了在问题2中命名的错误。 – AlmostGr

+0

你为什么认为这些名字应该存在? –

回答

0

变量“结果”是列表的列表,以便在这部分

for i in results: 
    if results[5] == 1: 
     Listposblocks_COG1.append(i) 

“的结果[5]”大概是从来没有1,因此Listposblocks_COG1为空,所有的时间。 也许你想做到这一点:

for i in results: 
    if i[5] == 1: 
     Listposblocks_COG1.append(i) 

,可能无法打印其他2所列出的原因是因为他们是在“如果”的范围和你打印出来的存在。所以如果你想打印它们,你应该在“if”范围之外定义它们,或者把打印件放在“if”之内。 喜欢的东西:

if Start_index_nulzero == 5: 
    Listposblocks_COG1 = [] 
    for i in results: 
     if i[5] == 1: 
      Listposblocks_COG1.append(i) 

    Listposblocks_COG2 = [] 
    if type(results[6]) == int: 
     for i in results: 
      if i[6] == 1: 
       Listposblocks_COG2.append(i) 

希望这有助于。

+0

嗨,结果已经在第一行1。 我想添加(追加)整个行到Listposblocks_COG1索引5的列中有一个1。 打印代码是在if循环之外,所以它不能是问题。 – AlmostGr

+0

的确,打印代码在外面。但是列表定义在里面。你有没有尝试过我发布的代码?因为当你访问结果[5]时,你正在访问一个不是整数的列表......所以它从不是1.“结果”是列表的列表。你在为结果做我,我[5]是你实际想要搜索的整数。 –

+0

谢谢,现在的确我现在放在'我'而不是'结果'它正在工作。但是,为什么我不能打印Listposblocks_COG2和Listposblocks_COG3。它应该保存在Listposblocks_COG2/3中吗?我不能在将来的脚本中随时打印这些列表吗? – AlmostGr