簡體   English   中英

根據項條件在兩個列表中查找索引

[英]Find indexes on two lists based on items condition

可以說我有兩個清單。 它們是從-5到5的書籍評級列表。

我想知道list1的元素是>= 1而list2的元素== 0 ,例如。

list1 = [3, 3, 1, 0, 3, 0, 3, 0, 0, -3, 0, 5, 3, 0, 1, 0, 0, 5, 3, 0, 0, 0, 0, 1, 0, 3, 0, 1, 0, 0, 3, 5, 3, 3, 0, 0, 0, 5, 0, 5, 0, 3, 3, 0, -3, 0, 0, 5, 1, 5, 3, 0, 3, 0, 0]
list2 = [5, 0, 0, 0, 0, 0, 5, 0, 0, 1, 0, 5, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 3, 0, 5, 0, 0, 0, 0, 5, 5, 5, 3, 0, 0, 0, 3, 0, 0, 0, 5, 3, 0, 0, 0, 0, 5, 0, 5, 3, 0, 0, 0, 0]

list1[1] = 3list2[1] = 0 ,我希望能夠找到發生這種情況的所有不同索引。

對不起,如果這令人困惑,但我真的不知道怎么說這個。

>>> [i for i, v in enumerate(list1) if v>=1 and list2[i]==0]
[1, 2, 4, 14, 18, 27, 39, 48, 52]

另一個變種:

>>> [i for i, (l1, l2) in enumerate(zip(list1, list2)) if l1 >= 1 and l2 == 0]
[1, 2, 4, 14, 18, 27, 39, 48, 52]
>>>idx_list = [i for i in range(len(list1)) if list1[i] > 1 and list2[i] == 0]

我發現這更具可讀性。

>>> from itertools import count
>>> [i for i,one,two in zip(count(0), list1, list2) if one >= 1 and two == 0]
[1, 2, 4, 14, 18, 27, 39, 48, 52]

這是itertools.count doc

使用NumPy數組,可以使用邏輯索引:

 import numpy as np
 list1 = np.array([1, -1, 0, 0, 1])
 list2 = np.array([0, 5, 0, 0, 0])

 # Option 1, multiply the logicals together.
 inds = np.where( (list1 >= 1)*(list2 == 0) )[0]

 # Option 2, pure logicals.
 inds = np.where( (list1 >= 1) & (list2 == 0) )[0]

現在inds[0] = 0inds[1] = 4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM