是否存在直接执行此操作的方法?
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 有更紧凑的形式,但我想象您的代码的实际情况(而不是人为的示例)要做的事情至少稍微复杂一些,因此使用if 和 else block 通过多个语句变得更具可读性。
关于python - 如何获取使用 "if element in list"找到的元素的索引或元素本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452093/