获取原始列表中列表项的索引

Get index of list item inside of original list

我有一个类似于下面的列表:

l = [["abc", 4, 3], ["def", 0, 0], ["ghi", 1, 2], ["def", 0, 0]]

我将变量设置为 l[1]。考虑到有重复项,是否可以在原始列表中获取该变量的索引?

示例return值:1(因为我设置的变量是l[1]

如果我理解问题你想拥有所有重复项的索引。你可以这样做

for x,y in enumerate(l):
    if y == value:
         index.append(x)

如果您只需要第一个索引,您可以使用

list.index(value)

它将return值的第一次出现

所以如果我理解正确的话:

l = [["abc", 4, 3], ["def", 0, 0], ["ghi", 1, 2], ["def", 0, 0]]
item = l[3]
assert l.index(item) == 3  # this won't work because l.index(item) will return 1

您希望这会起作用,但它不会导致项目索引 1 与项目索引 3 相同。

您可能应该使用不同的数据结构来解决这个问题。但是,您可以尝试使用对象标识比较来查找完全相同的列表,而不是对象相等性,这将与包含相同项目的不同列表匹配。例如,像这样:

l = [["abc", 4, 3], ["def", 0, 0], ["ghi", 1, 2], ["def", 0, 0]]
item = l[3]
assert next(index for index, candidate in enumerate(l) if candidate is item) == 3

这是有效的,因为 is 运算符使用 object identity comparison 查找 item 引用的实际列表。