簡體   English   中英

在2D數組中查找值的索引

[英]Find the index of a value in a 2D array

這是我的代碼:

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

value = "Tragedy"

print(test_list.index(value))

結果我得到“ ValueError:'悲劇'不在列表中

我得出的結論是.index僅適用於一維數組? 但是那我該如何使2D陣列消失呢? 如果我將數組設為1D,則此代碼可以正常工作。 請幫助,但簡單來說,我是個初學者。

很抱歉在手機上格式化問題。 該陣列為我正確設置了。

遍歷列表,並在每個子列表中搜索字符串。

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

您還可以使用地圖運算符:

# 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))

您也可以使用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將為您列出所有出現的索引。

numpy數組可能會在您的特定情況下有所幫助

import numpy

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

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

暫無
暫無

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

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