我有两张单子:
all_words_merged = ['ego', 'femina', 'incenderare', 'tuus', 'casa', 'et',
'cutullus', 'incipere', 'et', 'wingardium', 'leviosa']
class_words_merged = ['femina', 'incenderare', 'incipere', 'wingardium']
我想获取all_words_merged
并删除发生在class_words_merged
中的任何实例。结果列表应为:
result = ['ego', 'tuus', 'casa', 'et', 'cutullus', 'et', 'leviosa']
我尝试了下面的代码,但它返回了一个空列表:
result = [x for x in class_words_merged if x[0] in all_words_merged]
也可以使用
filter
内置方法来完成,如下所示:list
对于Python3是必需的,因为filter
生成一个过滤器对象,而在Python2中,这不是必需的,只是:编辑:
当然,这不是优化的方法,因为您必须将生成器转换为列表,您可以通过时序配置文件来猜测:
您应该在
all_words_merged
上迭代,并且只包含不在class_words_merged
中的单词输出:
编辑
如果
class_words_merged
可以包含重复项,那么首先使用set
将提供更好的性能。你知道吗如果
class_words_merged
很大,首先将其转换为一个集合会加快速度:一些计时
100倍大:
先创建为集合:
反复浏览清单:
提示:
%timeit
和%%imeit
是我在Jupyter笔记本中使用的IPython魔术命令。你知道吗相关问题 更多 >
编程相关推荐