在二维数组中查找值的索引

2024-09-29 06:34:15 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

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

value = "Tragedy"

print(test_list.index(value))

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

我的结论是,索引只对一维数组有效?但是我该怎么做呢?如果我把数组设为1D,这段代码可以很好地工作。请帮忙,但简单地说,因为我是初学者。你知道吗

很抱歉在手机上出现格式化问题。这个阵列对我来说是正确的。你知道吗


Tags: andtest密码playindexvalue数组shakespeare
3条回答

也可以使用映射运算符:

# 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将给出所有引用的索引列表。你知道吗

循环浏览列表并在每个子列表中搜索字符串。你知道吗

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

相关问题 更多 >