检查第二个列表中是否存在第一个列表中元素的两倍并打印输出

时间:2019-02-06 13:33:37

标签: python list

假设

search()

比较public function search($params) { $query = Report::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => [ 'defaultOrder' => [ 'created' => SORT_DESC, ] ], 'pagination' => [ 'pageSize' => 100, ], ]); $this->load($params); if (!$this->validate()) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'created' => $this->created, 'updated' => $this->updated, 'closed' => $this->closed, 'user_id' => $this->user_id, 'status_id' => $this->status_id, 'location_id' => $this->location_id, 'typeperson_id' => $this->typeperson_id, 'field_cpfcnpj' => $this->field_cpfcnpj, ]); if ($this->start_date !== null && $this->end_date !== null) { $query->andFilterWhere( [ 'BETWEEN', new Expression( 'DATE_FORMAT(created_at,"%Y/%m/%d")' ), date("Y/m/d", strtotime($this->start_date)), date("Y/m/d", strtotime($this->end_date)), ] ); } $query->andFilterWhere(['between', 'closed', $this->start_closed, $this->end_closed]); return $dataProvider; } Currency::where('id', '>', 0)->update(['default' => 0]); 并打印List1 = [ 23, 45, 6, 7, 34] List2 = [46, 23, 1, 14, 68, 56] 中在List1中具有双值的元素

List2

4 个答案:

答案 0 :(得分:8)

尝试一下:

Output = [i for i in List1 if i*2 in List2]

答案 1 :(得分:3)

您可以将list2转换为一个集合以进行有效的查找,并使用具有上述条件的列表理解来获得所需的输出:

set2 = set(List2)
[i for i in List1 if i * 2 in set2]

答案 2 :(得分:1)

您已经有了答案,但是只是为了简单起见。基本上,您想遍历List1并检查List2中是否包含double值。如果是这样,请将元素添加到output数组中。

List1 = [ 23, 45, 6, 7, 34]
List2 = [46, 23, 1, 7, 14, 68, 56]

output = []

for i in List1:
    if i*2 in List2:
        output.append(i)

print output

答案 3 :(得分:1)

您已经得到答案。但是,仅出于娱乐目的,我想出了以下方法。我没有对这里列出的所有方法进行基准测试。这样做很有趣。这是一个有趣的问题,可以进一步研究。但是,仅出于此目的,我介绍了我所做的解决方案。

import numpy as np
l = np.array(List1) * 2
print(l)

## array([46, 90, 12, 14, 68])

print(set(l) & set(List2))
## {68, 46, 14}

l2 = set(l) & set(List2)

print([List1[list(np.nonzero(l == i))[0][0]] for i in l if i in l2])
## [23, 7, 34]

它使用numpy的广播以及Python set的快速交集操作。如果两个列表很大,这可能很有用。