Edw*_*gin 4 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)
Run Code Online (Sandbox Code Playgroud)
第一次尝试有效,但不会删除"你+朋友",其中包含过滤词,但完全等于列名,因此保留.我的最后一次尝试给出'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']
Run Code Online (Sandbox Code Playgroud)
值得注意的是(从评论中)你可以放弃[]调用中的内部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']
Run Code Online (Sandbox Code Playgroud)