python - 在python中使用集合和列表创建一个新列表
问题描述
我有以下动态数据,但下面是它可能的示例:
# An incoming List of lists with only ints
# For exampe the incoming_list could be:
incoming_list = [[1,2]. [3]]
# The indexes are like so:
0: [1,2]
1: [3]
然后我有一个 check_list ,其中包含一些示例数据(将是动态的),如下所示:
# A List[int] for check_list
check_list= [3]
然后,如果任何传入列表数据在其索引中,我需要获取incoming_list 上的第一个int:
# If the following were input:
incoming_list = [[1,2]. [3]]
check_list= [3]
# Then a new_list would be:
new_list = [3] because incoming_list has a list with 3 in it, and the
first element of that list is 3
##############################################################
# Another example ff the following were input:
incoming_list = [[1,2]. [3]]
check_list= [2,3]
# Then a new_list would be:
new_list = [1,3] because incoming_list has a 2 in the first index and
its first value is 1 and because incoming list has a 3 in the second index
and its first and only value is 3
我试图用一组列表组合来做到这一点,但我认为列表部分把它搞砸了:
new_list = list(set(v for k, v in incoming_lists if int(k) in check_list))
任何想法如何使这些干净和优雅?
解决方案
O(1)
在一般情况下,将列表预处理为可以在线性时间内完成的查找结构可能是有意义的:
lookup = {}
for lst in reversed(incoming_list):
for x in lst:
lookup[x] = lst[0]
然后你可以简单地使用这个:
result = [lookup[x] for x in check_list]
推荐阅读
- javascript - 为什么我必须触发两次点击事件才能触发正确的 dataLayer?
- javascript - React - 路由器:无法访问嵌套路由
- apache-spark - 在 Pyspark 中转置从解析的 XML 生成的数据框列
- windows - PowerShell 用“)”标记我的错误
- javascript - 使用 JavaScript 函数关闭当前窗口
- php - 在每个结束标记后设置一个新行
- wordpress - 将客户输入的自定义 URL 添加到 WooCommerce 中的管理订单页面
- windows - 通过 DISM 按需离线安装 Windows RSAT 功能不起作用
- google-app-engine - 为什么 Google App Engine Standard Edition for Java 会创建 __static__ 文件夹并将部署到项目的文件数量增加一倍?
- cookies - Cookies law/gdpr 如何影响 Rectaptcha 和 A/B 测试?