首页 > 解决方案 > 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')]

最快的方法是什么?

标签: pythontuplesitertools

解决方案


您甚至可以跳过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')]

推荐阅读