![](/img/trans.png)
[英]Given an index in a flattened list, get the index of the original list item
[英]Get index of list item inside of original list
我有一個類似於下面的列表:
l = [["abc", 4, 3], ["def", 0, 0], ["ghi", 1, 2], ["def", 0, 0]]
我將一個變量設置為l[1]
。 考慮到有重復項,是否可以在原始列表中獲取此變量的索引?
示例返回值:1(因為我設置的變量是l[1]
)
所以如果我理解正確:
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
運算符使用對象標識比較來查找item
引用的實際列表。
如果我理解問題您想要擁有所有重復項的索引。 你可以這樣做
for x,y in enumerate(l):
if y == value:
index.append(x)
如果你只想要第一個索引,你可以使用
list.index(value)
它將返回值的第一次出現
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.