简体   繁体   English

根据项条件在两个列表中查找索引

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

Lets say I have two lists. 可以说我有两个清单。 They are lists of ratings of books on a scale from -5, to 5. 它们是从-5到5的书籍评级列表。

I want to know when list1's element is >= 1 and list2's element == 0 , so for example. 我想知道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] = 3 and list2[1] = 0 , I want to be able to find all the different indexes of where this happens at. list1[1] = 3list2[1] = 0 ,我希望能够找到发生这种情况的所有不同索引。

Sorry if this is confusing but I don't really know how else to word this. 对不起,如果这令人困惑,但我真的不知道怎么说这个。

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

Another variant: 另一个变种:

>>> [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]

I found this more readable. 我发现这更具可读性。

>>> 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]

And here's the itertools.count doc . 这是itertools.count doc

Using NumPy arrays, this is do-able with logical indexing: 使用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]

Now inds[0] = 0 and inds[1] = 4 . 现在inds[0] = 0inds[1] = 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM