列表理解和看似等效的Python for循环返回略有不同的列表

时间:2018-02-22 16:33:05

标签: python list-comprehension

下面我尝试使用list comprehension active_apps_reported_2和Python for循环active_apps生成相同的列表。我生成的列表来自应用程序的reported_apps的2D列表和已提交报告len(active_apps_reported) == 5875的2D应用程序列表。我的目标是确定已提交报告的活动应用程序。两个最终列表报告了相同的4482个唯一值;但是,len(active_apps_reported_2) == 5880active_apps_reported = [app for app in active_apps if any(app[0:2] == other[0:2] for other in reported_apps)] active_apps_reported_2 = [] for app in active_apps: for other_app in reported_apps: if app[0:2] == other_app[0:2]: active_apps_reported_2.append(app) else: continue 。差异似乎很小,但我很困惑,因为两个列表都是从相同的两个2D列表生成的。

  //delete liked favorites that the ads are invalid

   $check_favorites = "SELECT favorite_id, ads_id FROM public_favorites";
   $check_favorites_qry = $con->query($check_favorites);   

while($checked = $check_favorites_qry->fetch_assoc()) {

      $invalid_ads = "SELECT ads_id FROM public_ads WHERE ads_id = '". $checked['ads_id'] ."'";
      $invalid_ads_qry = $con->query($invalid_ads);

      if($invalid_ads_qry->num_rows < 1) {

          while($unavailable = $invalid_ads_qry->fetch_assoc()) {

              $update_dates = "DELETE FROM public_favorites WHERE favorite_id = '". $checked['favorite_id'] ."'";
              $query_updated = $con->query($update_dates);                 

          }
      }        
} 

1 个答案:

答案 0 :(得分:2)

我的建议是对两种编码方法都有相同的结果:

len(active_apps_reported) > len(active_apps_reported_2)

但是,我真的认为你的帖子并不完全一致:你写了type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) } type reverse struct { // This embedded Interface permits Reverse to use the methods of // another Interface implementation. Interface } ,但我本来期望相反。