繁体   English   中英

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

[英]Pythonic way of filtering out a list of strings from another list of strings

还在学习并且以前使用嵌套循环完成了这项工作,但我想知道是否有一种从另一个字符串列表中过滤掉字符串列表的漂亮而精简的方法。 我基本上有一个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)

第一次尝试有效,但不会删除“你+朋友”,其中包含过滤词,但完全等于列名,因此保留。 我的最后一次尝试给出'e在分配之前被引用'

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

谢谢你们和gals

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

>>> 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']

可能更有效的方法是将标记列表转换为set()

然后,您可以执行类似filteredSet = setA - setB ,这将生成setA的副本,其中setB中的元素已从其中删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM