Pythonic从另一个字符串列表中过滤掉字符串列表的方法

时间:2016-05-04 19:02:18

标签: python list-comprehension

仍在学习并且以前使用嵌套循环完成了这项工作,但我想知道是否有一种从另一个字符串列表中过滤掉字符串列表的漂亮而精简的方法。 我基本上有一个300列的pandas数据帧,如果它们有一些关键词,想要从数据帧中删除一些列。然后计划是指定列标题以生成新的数据帧。

以下是我对列表理解的尝试:

filter_array = ['hi', 'friend']
col_names = ['nice', 'to', 'meet', 'you' + 'friend']
p = [i for i in col_names if i not in filter_array]
print(p)
p = [i for i in col_names if e for e in filter_array e not in i]
print(p)
p = [i for i in col_names if e not in i for e in filter_array]
print(p)

第一次尝试有效,但不会删除过滤词出现但与col名称完全相同的“你+朋友”,因此保留。 我的最后一次尝试是'e在分配之前被引用'

为什么没有pythonic的标签! :)

谢谢大家和女士们

2 个答案:

答案 0 :(得分:5)

我认为这可以为您提供您正在寻找的结果:

>>> filter_array = ['hi', 'friend']
>>> col_names = ['nice', 'to', 'meet', 'you' + 'friend']
>>>
>>> [c for c in col_names if all([f not in c for f in filter_array])]
['nice', 'to', 'meet']

值得注意的是(从评论中)您可以在调用[]时删除内部all,以将内部列表理解更改为生成器表达式。列表推导将使用更多内存,但是如果必须消耗生成器的所有步骤(all不能短路时),它将优于生成器表达式。您也可以使用any代替all来反转逻辑。例如:

>>> [c for c in col_names if all(f not in c for f in filter_array)]
['nice', 'to', 'meet']
>>> [c for c in col_names if not any(f in c for f in filter_array)]
['nice', 'to', 'meet']

答案 1 :(得分:0)

可能更有效的方法是将您的代码列表转换为@media screen and (max-width : 840px) { .sidenav,#menu_button { display: none; } #bigwrapper { width: 90%; margin-left: 5%; } }

然后,您可以执行set()之类的操作,这将生成setA的副本,其中setB中的元素已从中删除。

相关问题