我有2个列表,例如说
list1 = ['abc', 'xyz', 'cat', 'xyz', 'abc', 'pqr', 'dog']
list2 = ['xyz', 'dog', 'pqr', 'abc', 'cat']
我想通过用list1
中元素的索引替换list2
来创建新列表,例如
list3 = [3, 0, 4, 0, 3, 2, 1]
我应该在这里提到,我实际上是从list2
那里得到list1
的
list2 = list(set(list1))
因此list2
没有重复项,并且具有list1
的所有元素。
我想知道以Python方式获得list3
的最快方法。
到目前为止,我已经尝试了两种方法:
1>基本的.index
方式
list3 = [list2.index(item) for item in list1]
2>使用以元素为键的字典和以值为索引的字典
d = {list2[i]:i for i in range(len(list2))}
list3 = [d[item] for item in list1]
答案 0 :(得分:0)
如果您担心要查找重复值,只需先创建一个索引:
>>> idx={e:list2.index(e) for e in list2}
或者:
>>> idx={e:n for n,e in enumerate(list2)}
然后:
>>> [idx[e] for e in list1]
[3, 0, 4, 0, 3, 2, 1]
答案 1 :(得分:0)
//---- Angular 2 Http Service Example ----
import {Injectable} from "@angular/core";
import {Http, Headers} from "@angular/http";
const AWS = require("aws-sdk");
@Injectable()
export class ApiGatewayService {
constructor(private http:Http){
let creds = new AWS.CognitoIdentityCredentials({
IdentityPoolId: "eu-west-1:xxx-xxxx-xxxxxxxx"
});
AWS.config.update({
region: 'eu-west-1',
credentials: creds
});
AWS.config.credentials.get((err) => {
if(err) throw err;
let httpRequest = new AWS.HttpRequest("https://xxxxx.execute-api.eu-west-1.amazonaws.com/v1/my/api", "eu-west-1");
httpRequest.method = "POST";
httpRequest.headers.host = "xxxxx.execute-api.eu-west-1.amazonaws.com";
httpRequest.headers['Content-Type'] = "application/json";
httpRequest.body = JSON.stringify({
data: {
username: 'foo',
password: 'bar',
applicationName: 'biz',
}
});
let v4signer = new AWS.Signers.V4(httpRequest, "execute-api", true);
v4signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate());
//Create a headers object from the AWS signed request
let headers = new Headers();
for(let key of Object.keys(httpRequest.headers)){
headers.set(key, httpRequest.headers[key]);
}
headers.delete('host'); //Browser throws a warning if attempting to set host header
this.http.post(httpRequest.endpoint.href, httpRequest.body, {
method: httpRequest.method,
search: httpRequest.endpoint.search,
headers: headers
}).subscribe((data)=>{
console.log(data); //Success
});
})
}
}