在2D数组中查找值的索引

时间:2019-02-11 18:44:03

标签: python arrays list indexing 2d

这是我的代码:

test_list= [
    ["Romeo and Juliet","Shakespeare"],
    ["Othello","Play"],
    ["Macbeth","Tragedy"]
]

value = "Tragedy"

print(test_list.index(value))

结果是我收到“ ValueError:'悲剧'不在列表中

我得出的结论是.index仅适用于一维数组?但是那我该如何使2D阵列消失呢?如果我将数组设为1D,则此代码可以正常工作。请帮忙,但简单来说就是我的初学者。

在手机上格式化问题的道歉。阵列对我来说是正确的。

4 个答案:

答案 0 :(得分:1)

浏览列表,并在每个子列表中搜索字符串。

Testlist = [
               ["Romeo and Juliet","Shakespeare"],
               ["Othello","Play"],
               ["Macbeth","Tragedy"]
               ]

Value = "Tragedy"

for index, lst in enumerate(Testlist):
  if Value in lst:
    print( index, lst.index(Value) )

答案 1 :(得分:0)

您还可以使用地图运算符:

# Get a boolean array - true if sublist contained the lookup value
value_in_sublist = map(lambda x: value in x, test_list)

# Get the index of the first True
print(value_in_sublist.index(True))

答案 2 :(得分:0)

您也可以使用numpy

import numpy as np
test_list = np.array(test_list)
value = 'Tragedy'
print(np.where(test_list == value))

输出:

(array([2]), array([1]))

如果一个元素有多次出现,那么np.where将为您列出所有出现的索引。

答案 3 :(得分:0)

numpy数组可能会在您的特定情况下有所帮助

import numpy

test_array = numpy.array(Testlist)
value = "Tragedy"

numpy.where(test_array==value)
# you will get (array([2]), array([1]))
相关问题