Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表字符串的开头与白名单进行比较_Python_Performance_List_Python 3.x_Compare - Fatal编程技术网

Python 将列表字符串的开头与白名单进行比较

Python 将列表字符串的开头与白名单进行比较,python,performance,list,python-3.x,compare,Python,Performance,List,Python 3.x,Compare,我想将列表与白名单进行比较。我现在做的是: >>> whitelist = ("one", "two") >>> my_list = ["one", "two foo", "two bar", "three"] >>> for item in my_list: ... if not item.startswith(whitelist): ... print(item) three 有更有效/更好的方法吗?您可以使用列

我想将列表与白名单进行比较。我现在做的是:

>>> whitelist = ("one", "two")
>>> my_list = ["one", "two foo", "two bar", "three"]
>>> for item in my_list:
...     if not item.startswith(whitelist):
...         print(item)
three

有更有效/更好的方法吗?

您可以使用列表理解:

print '\n'.join([item for item in my_list if not item.startswith(whitelist)])
>>> [item for item in my_list if not item.startswith(whitelist)]
['three']

这几乎就是你做这件事的方式——如果你想测试元素是否与白名单完全匹配,那么它就有点不同了,你可能会根据你想对这些项目做什么来重新进行理解。。。但除此之外,这是一个正确的想法。@mgilson谢谢,这是一个很好的评论来证实这个想法。你想打印它们还是收集它们?@AshwiniChaudhary打印声明只是一个例子,并不真正相关。