让我们说我有两个清单。它们是从-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] = 3
和list2[1] = 0
,我希望能够找到发生这种情况的所有不同索引。
很抱歉,如果这令人困惑,但我真的不知道怎么说这个。
答案 0 :(得分:11)
>>> [i for i, v in enumerate(list1) if v>=1 and list2[i]==0]
[1, 2, 4, 14, 18, 27, 39, 48, 52]
答案 1 :(得分:7)
另一种变体:
>>> [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]
答案 2 :(得分:4)
>>>idx_list = [i for i in range(len(list1)) if list1[i] > 1 and list2[i] == 0]
答案 3 :(得分:2)
我发现这更具可读性。
>>> 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]
答案 4 :(得分:2)
使用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] = 0
和inds[1] = 4
。