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

标签 python list tuples

是否存在直接执行此操作的方法?

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

最佳答案

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 block 通过多个语句变得更具可读性。

关于python - 如何获取使用 "if element in list"找到的元素的索引或元素本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452093/

相关文章:

list - F#返回元组列表中中间值最大的3个元素元组

python - pytest 添加选项以跳过 fixture 设置

python - 如何在 OpenCV 的特征提取过程中忽略图像的一部分?

python - 列表索引超出范围,我不明白为什么?

Python循环比较字典列表与另一个字典

python-3.x - Pandas:从多列创建一个元组列

python - 如何从匹配的表达式中找到特定的单词?

python - Bot 在 Top.gg 上投票时没有发送 DM

python - 使用 `set` 从列表创建一个集合与解压到大括号中

python - 更改元组列表中元组的第一个值