删除重复值并保持元素的顺序

时间:2017-12-06 17:23:22

标签: python sorting duplicates

我们如何在保存订单的同时从list2删除list1list1=[(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)] list2=[(1,1),(1,2)] list1 = list(set(list1) - set(list2)) print (list1) 之间的重复值?

我的代码示例:

import { Injectable } from '@angular/core';

import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {

  private isUserLoggedIn;  
  public username = String;
  result:any;

  constructor(private _http: Http) { 
    this.isUserLoggedIn = false;
  }
   getUsers() {
    return this._http.get("/api/users")
      .map(result => this.result = result.json().data);
  }
  addUser(newUser){
        console.log("add new user" + newUser);
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this._http.post('/api/users', JSON.stringify(newUser), {headers: headers})
        .map(res => res.json());
    }


  setUserLoggedIn(name) {
    this.isUserLoggedIn = true;    
    sessionStorage.setItem('username', name);
    this.username = name;
  }
  getNameUserLoggedIn()
  {
    return sessionStorage.getItem('username');
  }
  getUserLoggedIn() {
    return this.isUserLoggedIn;
  }

}

输出

  

[(5,4),(1,3),(3,4),(4,7)]

预期输出

  

[(1,3),(3,4),(5,4),(4,7)]

2 个答案:

答案 0 :(得分:3)

使用列表理解:

list1 = [item for item in list1 if item not in list2]

如果list2可能大于几个项目,请将其转换为set以便更快地检查:

set2 = set(list2)
list1 = [item for item in list1 if item not in set2]

请注意,上述任何一个代码段都会在list1中保留任何重复的项目(即,如果list1中的两个项目相同,但不在list2中)。如果您想消除list1中的内部重复项,这是原始解决方案的行为,这将仅保留每个重复项的第一次出现:

set1 = set(list1)
set2 = set(list2)
list1 = [set1.remove(item) or item for item in list1
         if item in set1 and item not in set2]

答案 1 :(得分:1)

好吧,一个集合在内部散列元素,因此永远无法维持顺序。如果列表中的元素保证是唯一的,即它们只出现一次,您可以使用该集来过滤所需的元素:

In [26]: list1 = [(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2 = [(1,1),(1,2)]
    ...: unique = set(list1) - set(list2)
    ...: list1 = [x for x in list1 if x in unique]
    ...: print (list1)
    ...: 
[(1, 3), (3, 4), (5, 4), (4, 7)]

如果列表中可以多次出现相同的元素,并且您需要跟踪不同元素的唯一数量,那么您现在还需要保持计数。由此,逻辑看起来像:

In [29]: list1=[(1,1),(1,1),(1,2),(1,3),(3,4),(5,4),(4,7)]
    ...: list2=[(1,1),(1,2)]
    ...: 
    ...: from collections import Counter
    ...: 
    ...: count = Counter(list1)
    ...: for element in list2:
    ...:     if element in count:
    ...:         count[element] -= 1
    ...: 
    ...: result = []
    ...: for element in list1:
    ...:     if count.get(element, 0) > 0:
    ...:         count[element] -= 1
    ...:         result.append(element)
    ...: 
    ...: print (result)
    ...: 
[(1, 1), (1, 3), (3, 4), (5, 4), (4, 7)]