python - 如何检查一个项目是否存在于内部列表中并在包含它的相应外部列表中获取列表项?
问题描述
我有一个这样的列表:
[[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
解决方案
您可以使用列表推导来检查子列表是否包含给定的数字,然后获取相应的外部列表值:
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'
推荐阅读
- angular - Angular 9 的新手,重定向有效,但直接转到 URL 无效
- python-3.x - 我正在尝试在 scrapy 中加入 URL 但无法这样做
- android - 几个库的androidx迁移问题
- amazon-web-services - AWS S3 -> Elastic Beanstalk - 混合内容错误
- dart - 如何在 Dart 中将 utf8 转换为 ISO-8859-1?
- automation - Vividus 版本策略
- javascript - 根据有序的值列表对对象数组进行排序
- ios - 停止 QLPreviewController 在呈现的视图控制器中调整大小
- ringcentral - RingCentral Meetings API - 用户需要有 [Meetings] 权限
- javascript - 以下场景的编码标准需要明确或建议