我有一个这样的清单:
[[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
我想要这样的东西:
检查内部列表中是否存在2(可以包含多个项),然后获取对应的外部列表值(始终为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
如果您希望输出与您所描述的完全相同:
values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
search_value = 0
print(f"Search for {search_value}")
found = []
for outer, inner in values:
if search_value in inner:
found.append(outer)
if found:
print(f"{search_value} was found with ", end="")
print(*found, sep=" and ")
搜索0
0被发现为2和4
如果您只需要知道为其找到搜索值的外部值:
values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
search_value = 0
for outer, inner in values:
if search_value in inner:
print(outer, end=" and ")
2和4
用列表推导将两个for循环替换为一个简单的衬纸:
values = [[0, [2]], [1, [4]], [2, [0, 6]], [3, [3]], [4, [0, 6]]]
search_value = 0
print(*[outer for outer, inner in values if search_value in inner], sep=", ")
2 4
适用于Python 3.6+
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句