对于循环在python中只运行一次

时间:2015-07-10 06:39:27

标签: python pymongo

以下是我的代码:

< asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"
                OnClientClick="return saveChanges()" />   **Script:**  var isPostBack=false; function saveChanges() { if(!isPostBack){
         PageMethods.savePageChanges(tableData, updateContent_OnSucceeded,      updateContent_onFailure);
  return false;
  }else{ 
     return true;}
   }




    function updateContent_OnSucceeded(retval) {
       isPostBack=true;
      $('# <%=btnSave.ClientID%>).click();
    }

    function updateContent_onFailure(val) {
        alert("Error: " + val.get_message());

    }**CS:**[System.Web.Services.WebMethod]
public static bool savePageChanges(List<List<string>> rowDataArraySeries)
{}

我在alb集合中有以下数据:

import pymongo
import sys

client=pymongo.MongoClient('localhost',27017)
db=client.test 

try:              
     cursor= db.alb.find()         
     cursor1=db.img.find()             
     cntr=db.alb.count()        
     print "looping starts..."     
     for im in cursor1:                                                                                                        
         id1=im['_id']
         cnt=0
         print id1         
         for image in cursor:
             ig=image['images']
             print "image value:" , ig
             print "id value:" , id1
             if (id1 == ig):
                break;
             else:
                cnt=cnt+1
                print "count value", cnt
                if (cnt == cntr):
                   print "removing..."
                   db.img.remove({'_id':id1})
                   print id1
                   print cnt

except Exception as e:
     print "unexpected error", type(e),e

我在img集合中有以下内容:

id:0 images:366
id:1 images:367
id:2 images:368
id:3 images:369
id:4 images:370
id:5 images:380
id:6 images:371
id:7 images:372

基本上来自上面的代码id:365 id:345 id:372 id:370 id:371 id:380 id:381 id:365id:345应该从img集合中删除,但我的代码只删除了img集合中的id:381

请帮我纠正此代码中的错误.....

4 个答案:

答案 0 :(得分:1)

有更好的方法。例如,这样的事情:

# Get all image identifiers
alb_images = [image['images'] for image in cursor]

# Find the ones to remove
images_to_remove = [im for im in cursor1 if im['_id'] not in alb_images]

完成上述操作后,images_to_remove应包含要从img集合中删除的图片。

[注意:这可能不是最有效的,也不是最恐怖的方式。]

答案 1 :(得分:1)

这样可行。这是因为当您调用generator 时生成db.alb.find(),当您在for中迭代生成器值时,生成器值已用尽循环所以第二次迭代时它没有任何值,所以只有循环运行一次

import pymongo
import sys

client=pymongo.MongoClient('localhost',27017)
db=client.test 

try:              

    cursor1=db.img.find()             
    cntr=db.alb.count()        
    print "looping starts..."     
    for im in cursor1:                                                                                                        
        id1=im['_id']
        cnt=0
        print id1 
        cursor= db.alb.find()   #move it here      
        for image in cursor:
            ig=image['images']
            print "image value:" , ig
            print "id value:" , id1
            if (id1 == ig):
                break;
            else:
                cnt=cnt+1
                print "count value", cnt
                if (cnt == cntr):
                print "removing..."
                db.img.remove({'_id':id1})
                print id1
                print cnt

except Exception as e:
    print "unexpected error", type(e),e

答案 2 :(得分:1)

import pymongo
import sys

client=pymongo.MongoClient('localhost',27017)
db=client.rop 

try:

   cntcur=db.albums.aggregate([{"$unwind":"$images"},{"$group":{"_id":"null","count":{'$sum':1}}}])
   cursor1=db.images.find()    

   for im in cursor1:         
       id1=int(im['_id'])
       cnt=0         
       cursor= db.albums.aggregate([{"$unwind":"$images"}])
       print id1         
       for image in cursor:
           print "moving to images collection"             
           ig=image['images']
           if (id1 == ig):
              break;
           else:
              cnt=cnt+1              
              if (cnt == cntr):
                 print "removing"  
                 db.images.remove({'_id':id1})                

 except Exception as e:
     print "unexpected error", type(e),e

对于上面的代码,我得到的字符串索引必须是整数。我得到的是ig = image [&#39; images&#39;]

答案 3 :(得分:0)

我不知道你的代码在哪里失败。将调试语句写在正确的位置,这样就可以获得代码失败的地方。

e.g。

>>> for i in range(1,5):
...     print "Debug 1- i: ", i
...     for j in range(10,15):
...         print "Debug 1.1- j ", j
...         if j==13:
...             break
  1. 代码打印长度为cursor1(我认为通过计数法)
  2. 删除语句后,
  3. 打印cursor1值,即db.img.remove({'_id':id1})
  4. 在所有流程之后,您还可以从img中删除一个 db.img.remove({'_id':id1})

    创建保存id1值的列表,在处理完毕后,只需从db.img

    中删除列表的所有ID
    remove_ids = []
    
    # remove statement, append id value to list
    remove_ids.append(id1)
    
    # After process do 
    for id in remove_ids:
        db.img.remove({'_id':id})