我知道如果我只有两个字符串,使用x in y
进行检查就行了。如果我只是想检查一个字符串是否在列表中的任何字符串中,我只需要使用for
循环。
但是,检查第一个列表中的任何字符串是否是第二个列表中字符串的子字符串的最pythonic /有效方法是什么?
一个例子是:
notPresent = []
present = []
listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Ryan', 'Jam', 'Jamesses', 'Jamboree']
notPresent = ['Ryan', 'Jam', 'Jamboree']
present = ['Rick', 'Ricky', 'Jamesses']
我将同时使用present
和notPresent
字词。
答案 0 :(得分:1)
listA = ['Rick', 'James']
listB = ['Rick', 'Ricky', 'Ryan', 'Jam', 'Jamesses', 'Jamboree']
present = {i for i in listB if any(j in i for j in listA)}
notPresent = set(listB) - present # difference of two sets
print(present)
# {'Rick', 'Ricky', 'Jamesses'}
print(notPresent)
# {'Jamboree', 'Ryan', 'Jam'}
any
有助于避免在找到匹配后运行整个迭代长度,并且set
可以从第一个生成补充集notPresent
。
答案 1 :(得分:1)
最快的方法可能是将第一个列表变成一个集合
$url = "https://onfleet.com/api/v2/auth/test";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, 'xxxxxxxxxxxxxxxxxxxxxx:');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
然后,对于setA = set(listA)
中的每个字符串,检查其子字符串是否在listB
中。
setA
答案 2 :(得分:0)
我会这样说:
var timersToReject = [];
var p1 = new Promise((resolve, reject) => {
setTimeout(v => {
console.log("resolving " + v);
resolve(v);
}, 1000, "one");
});
var p2 = new Promise((resolve, reject) => {
setTimeout(v => {
console.log("resolving " + v);
resolve(v);
}, 2000, "two");
});
var p3 = new Promise((resolve, reject) => {
setTimeout(v => {
console.log("resolving " + v);
resolve(v);
}, 3000, "three");
});
var p4 = new Promise((resolve, reject) => {
timersToReject.push(setTimeout(() => {
console.log('Don\'t show this after a reject!');
resolve();
}, 4000));
});
var p5 = new Promise((resolve, reject) => {
reject("reject");
});
Promise.all([p1, p2, p3, p4, p5]).then(value => {
console.log(value);
}, function(reason) {
console.log(reason)
timersToReject.forEach(t => clearTimeout(t));
});
所以基本上2个循环。并使用集合而不是列表(值的唯一性)...