简体   繁体   English

Python中列表索引相对于另一个列表的位置

[英]Position of indices of a list with respect to another list in Python

I am trying to locate the positions of indices of list B : (0,2),(2,1) with respect to list A .我正在尝试定位列表B的索引位置: (0,2),(2,1)相对于列表A But there is an error.但是有一个错误。 The desired output is attached.附加了所需的输出。

import numpy 
A=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
B=[(0,2),(2,1)]
C=B.index(A)
print("C =",C)

The error is错误是

<module>
    C=B.index(A)

ValueError: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] is not in list

The desired output is所需的输出是

[3,8]

I think what you're trying to do can be solved with a list comprehension as follows:我认为您尝试做的事情可以通过以下列表理解来解决:

import numpy 
A=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
B=[(0,2),(2,1)]
C= [A.index(element) for element in B]
print("C =",C)

That will return:这将返回:

[2,7]

If you want it to return your desired output, just do:如果您希望它返回所需的输出,只需执行以下操作:

C= [A.index(element)+1 for element in B]

To get the indices of the wanted pairs, you can do:要获取所需对的索引,您可以执行以下操作:

a=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
b=[(0,2),(2,1)]
c=[a.index(b_item) for b_item in b]
print("C =", c)

This will print [2,7] (indices starting from 0).这将打印 [2,7](从 0 开始的索引)。 Alternatively, if you want indices starting from 1 as output (result [3,8]):或者,如果您希望从 1 开始的索引作为输出(结果 [3,8]):

a=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
b=[(0,2),(2,1)]
c=[a.index(b_item)+1 for b_item in b]
print("C =", c)

Note that this will result in an error if the pair is not in list a.请注意,如果该对不在列表 a 中,这将导致错误。 You can work with try and except ValueError if you want to avoid errors.如果您想避免错误,可以使用tryexcept ValueError

Because you tag .因为您标记 You need to check each row of B with each row in A then use numpy.all and numpy.any .您需要检查B的每一行与A中的每一行,然后使用numpy.allnumpy.any (but you need to consider in python, Index start from zero, if you want [3,8]. you need to +1 result.) (但你需要在python中考虑,如果你想要[3,8],索引从零开始。你需要+1结果。)

>>> np.argwhere((A==B[:,None]).all(-1).any(0)).ravel()
array([2, 7])

Explanation:解释:

>>> A = np.asarray(A)
>>> B = np.asarray(B)
>>> A == B[:,None]
array([[[ True, False],
        [ True, False],
        [ True,  True],
        [False, False],
        [False, False],
        [False,  True],
        [False, False],
        [False, False],
        [False,  True]],

       [[False, False],
        [False,  True],
        [False, False],
        [False, False],
        [False,  True],
        [False, False],
        [ True, False],
        [ True,  True],
        [ True, False]]])

>>> (A==B[:,None]).all(axis=-1)
array([[False, False,  True, False, False, False, False, False, False],
       [False, False, False, False, False, False, False,  True, False]])

>>> (A==B[:,None]).all(axis=-1).any(axis=0) <- you want index of this array that have `True` value
array([False, False,  True, False, False, False, False,  True, False])

>>> np.argwhere((A==B[:,None]).all(axis=-1).any(axis=0))
array([[2],
       [7]])

>>> np.argwhere((A==B[:,None]).all(axis=-1).any(axis=0)).ravel()
array([2, 7])

Assuming A have no duplicates and B s are contained in the A , you can do this based on this answer :假设A没有重复项并且B包含在A中,您可以根据以下答案执行此操作:

(np.array(A)[:, None] == np.array(B)).all(-1).argmax(0) + 1
# [3, 8]

I have used +1 because indexing in Numpy arrays are starting from 0 .我使用+1是因为 Numpy 数组中的索引从0开始。 I recommend using numpy equivalent methods instead of loops because they will be much better than loops in terms of performance when working on large arrays.我建议使用 numpy 等效方法而不是循环,因为在处理大型数组时,它们在性能方面会比循环好得多。

Ok, Olli's answer is obviously correct, but I feel there are a few misundertandings in your post that need an explanation.好的,Olli 的回答显然是正确的,但是我觉得您的帖子中有一些误解需要解释一下。

C=B.index(A) asks for the position of A in B , which I believe is quite the opposite of what you want. C=B.index(A)询问AB中的位置,我认为这与您想要的完全相反。 Hence the error, A is not in B .因此错误, A不在B中。 But even A.index(B) would give an error, because once more B as a whole is not in A .但即使A.index(B)也会出错,因为B作为一个整体再次不在A中。

What you want to know is the position in A of each single element of B , or to be more precise of the first occurence in A of each element of B .您想知道的是B的每个单个元素在A中的位置,或者更准确地说是B的每个元素在A中的第一次出现。 So you need to iterate over each element of B and find its position in A .因此,您需要遍历B的每个元素并找到它在A中的位置。 This can be done in a few different ways, but the logic will always be the same这可以通过几种不同的方式完成,但逻辑总是相同的

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

相关问题 将列表解压缩到python中另一个列表的索引中 - Unpack a List in to Indices of another list in python Python列表作为列表索引 - Python list as a list indices 如何在python列表中找到彼此相邻的重复项并根据它们的索引列出它们? - How to find duplicates in a python list that are adjacent to each other and list them with respect to their indices? Python:在符合给定条件的第一个对象列表中找到位置 - Python: Find the position in a list of the first object that respect a given condition Python-与条件匹配的另一个列表的元素的索引列表 - Python - List of indices of elements of another list that match a condition 将索引列表传递给 Python 中的另一个列表。 正确的语法? - Passing a list of indices to another list in Python. Correct syntax? Python - 查找与另一个列表的元素匹配的列表元素的索引 - Python - Find the indices of elements of a list that match elements of another list 如何根据 Python 中另一个列表的(子列表)索引对列表进行分区 - How to partition a list based on (sublist) indices of another list in Python 在Python中以JSON列出索引 - List Indices in json in Python 根据 Python 中另一个列表的位置选择列表的位置 - Pick position of a list based on the position of another list in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM