根据条件从列表中删除元组

我想从列表中过滤掉所有没有特定元素的元组。具体来说,假设:

mylist = [("sagap", "apple", "orange"), ("apple", "orange", "crazy"), ("crazy", "orange"), ("orange", "banana", "do", "does"), ("apple", "do", "does", "something", "response")]

我想排除/删除列表中所有元组中不包含"apple"' and “orange”的元组

预期的结果应该是一个包含元组的新列表,如下所示:

mylist_new = [("sagap", "apple", "orange"), ("apple", "orange", "crazy") ] 

我会很感激你的帮助。请考虑在我的实际项目中,该列表大约有 10000 个元组。

理想情况下,我想要这样的东西:

list_of_items = ["apple, "orange"] 

search in my list which tuples have list_of_times and keep those in my list 

请考虑项目的数量不一定只有两个,可以是要考虑的任何大量项目

回答

你可以做

mylist_new = [t for t in mylist if 'apple' in t and 'orange' in t]
mylist_new = [t for t in mylist if 'apple' in t and 'orange' in t]

您的示例有一些错别字...将其更改为

In [9]: mylist = [("sagap", "apple", "orange"), ("apple", "orange", "crazy"), ("crazy", "orange"), ("orange", "banana", "do", "does"), ("apple", "do", "does", "something", "response")]

In [10]: mylist_new = [t for t in mylist if 'apple' in t and 'orange' in t]

In [11]: mylist_new
Out[11]: [('sagap', 'apple', 'orange'), ('apple', 'orange', 'crazy')]

UPDATE OP 更新问题以允许询问任意项目列表

为了适应这一点,我会简单地编写一个函数来检查循环中的那些

那么我原来的答案是

list_of_items = ["apple", "orange"] 
mylist_new = [t for t in mylist if contains_items(t, list_of_items)]


以上是根据条件从列表中删除元组的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>