如何获取使用“if element in list”找到的元素的索引或元素本身

2 投票
7 回答
590 浏览
提问于 2025-04-15 20:28

有没有直接的方法可以做到这一点呢?

if element in aList:
   #get the element from the list

我在想像这样做:

aList = [ ([1,2,3],4) , ([5,6,7],8) ]
element = [5,6,7]
if element in aList
     #print the 8

7 个回答

1
>>> aList = [ ([1,2,3],4) , ([5,6,7],8) ]
>>> element = [5,6,7]

如果你只想检查第一个元素是否存在

>>> any(element==x[0] for x in aList)
True

去找对应的值

>>> next(x[1] for x in aList if element==x[0])
8
1

(注意:这个回答是针对问题的文字部分,而不是代码中的示例,因为它们不太匹配。)

直接打印元素本身没有什么意义,因为你在测试中已经有这个元素了:

if element in lst:
    print element

如果你想要获取索引,可以使用索引方法:

if element in lst:
    print lst.index(element)

另外,如果你问这个问题是因为你想遍历一个列表,并对每个值和索引做一些操作,记得使用 enumerate 这个方法:

for i, val in enumerate(lst):
  print "list index": i
  print "corresponding value": val
3
L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]

for a, b in L:
  if a == element:
    print b
    break
else:
  print "not found"

但是听起来你想用字典:

L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]

D = dict((tuple(a), b) for a, b in L)
# keys must be hashable: list is not, but tuple is
# or you could just build the dict directly:
#D = {(1,2,3): 4, (5,6,7): 8}

v = D.get(tuple(element))
if v is not None:
  print v
else:
  print "not found"

请注意,虽然下面有更简洁的写法使用了next,但我想象你的代码实际情况(而不是一个人为的例子)可能会稍微复杂一些,所以在ifelse中使用一个代码块会让多个语句更易读。

撰写回答