[英]Python - Removing tuples by prefix and suffix from list
What's the fastest way to remove tuples from a python list (and update the list with the removed tuples) according to what the tuple starts with or ends with. 根据元组的开始或结束,从python列表中删除元组(并使用删除的元组更新列表)的最快方法是什么。
Example: 例:
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')]
I want to remove all tuples that starts with 'a'
OR ends with 'f'
so that my output will look as follows: 我想删除所有以'a'
开头或以'f'
结尾的元组,这样我的输出将如下所示:
[('b', 'd'),
('b', 'e'),
('c', 'd'),
('c', 'e')]
What is the fastest way to do it ? 最快的方法是什么?
You can even skip the itertools.product()
and just use one list-comprehension: 您甚至可以跳过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')]
with a list comprehension: 具有列表理解:
[t for t in tupl_lst if t[0]!='a' and t[1]!='f']
with filter
: 带filter
:
list(filter(lambda t: t[0]!='a' and t[1]!='f',tupl_lst))
Avoid the prefix ( a
) and suffix ( f
) altogether by iterating over slices of the lists. 通过遍历列表的各个部分,完全避免使用前缀( a
)和后缀( f
)。
[(x, y) for x in l1[1:] for y in l2[:-1]]
# [('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.