首页 > 解决方案 > 如何检查一个项目是否存在于内部列表中并在包含它的相应外部列表中获取列表项?

问题描述

我有一个这样的列表:

[[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]

我想要这样的东西:

检查内部列表中是否存在 2(可以包含超过 1 项),然后获取对应的外部列表值(始终为 1 项)的值,返回 0。

输入:

[[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]

输出(一些例子):

Search for 2
2 was found with 0

Search for 0
0 was found with 2 and 4

Search for 3
3 was found with 3

标签: python

解决方案


您可以使用列表推导来检查子列表是否包含给定的数字,然后获取相应的外部列表值:

num = 0
out = [i[0] for i in l if num in i[1]]
'{} was found with {}'.format(num, ', '.join(map(str,out)))
# '0 was found with 2, 4'

或者对于数字num=2

out = [i[0] for i in l if num in i[1]]
# '2 was found with 0'

上面的答案假设内部列表总是在第二个位置。如果不是这种情况,您可以改为:

out = [i[0] for i in l if num in sorted(i, key=lambda x: isinstance(x, list))[1]]
'{} was found with {}'.format(num, ', '.join(map(str,out)))
# '0 was found with 2, 4'

推荐阅读