python - Python - 通过列表中的前缀和后缀删除元组
问题描述
根据元组的开头或结尾,从python列表中删除元组(并使用已删除的元组更新列表)的最快方法是什么。
例子:
import itertools
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = list(itertools.product(l1, l2))
tupl_lst
Out[42]:
[('a', 'd'),
('a', 'e'),
('a', 'f'),
('b', 'd'),
('b', 'e'),
('b', 'f'),
('c', 'd'),
('c', 'e'),
('c', 'f')]
我想删除所有以'a'
OR 开头的元组,以'f'
使我的输出如下所示:
[('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e')]
最快的方法是什么?
解决方案
您甚至可以跳过itertools.product()
并只使用一个列表理解:
l1 = ["a", "b", "c"]
l2 = ["d", "e", "f"]
tupl_lst = [(x, y) for x in l1 for y in l2 if x!="a" and y!="f"]
#output
[('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]
推荐阅读
- javascript - 点击事件触发的次数越来越多
- android - SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 和 FLAG_TRANSLUCENT_STATUS 已弃用
- javascript - 在 JSON 文件中保存用户 ID 和值
- amazon-web-services - 将附加信息附加到 Lambda 超时消息?
- java - 无字段 sessionHostPortCache - Apache Commons Net 存储文件
- node.js - 如何从nodejs上传文件到firebase存储 - 客户端
- javascript - this.props.value 未定义 React
- python - 排除每周不出现的 ID
- swift - 为什么在 textViewDidBeginEditing 之前调用观察者 onKeyboardDisplayed
- python - 有效地将 DataFrame 行转换为列名和值组合的列表