我有一个字典列表,我想通过一个密钥' id'在python中排序。
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
constructor(private _http: Http) { }
getContacts() {
return this._http.get('assets/api/contacts.json')
.map((response: Response) => response.json());
}
}
我希望根据给定的排序顺序按特定顺序对它们进行排序:
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
contacts: any[]; <-- //this is where I defined my variable
errorMessage: string;
constructor (private _apiService: ApiService) {}
ngOnInit(){ this.getContacts();
console.log(this.contacts); <-- //This is where I get undefined
}
getContacts() {
this._apiService.getContacts()
.subscribe(contacts => this.contacts = contacts,
error => this.errorMessage = error);
}
}
我将如何在python3中执行此操作?
答案 0 :(得分:8)
使用key
参数和带有自定义排序顺序的列表。
sort_order = [30, 883, 547, 898]
items.sort(key=lambda d: sort_order.index(d['id']))
使用@Sphinx的建议,您可以事先为列表编制索引,以提高速度[{1}},而不是O(1)
O(n)
答案 1 :(得分:0)
您可以在一行中尝试不带循环:
items = [{'id' : 883},{'id' : 547},{'id' : 898},{'id' : 30},{'id' : 883}]
sorting_order=[30, 883, 547, 898]
print(sorted(items,key=lambda x:sorting_order.index(x['id'])))
输出:
[{'id': 30}, {'id': 883}, {'id': 883}, {'id': 547}, {'id': 898}]