我有一个值列表和一个字典.我想确保列表中的每个值都作为字典中的键存在.目前我正在使用两套来确定字典中是否存在任何值
unmapped = set(foo) - set(bar.keys())
Run Code Online (Sandbox Code Playgroud)
有没有更多的pythonic方式来测试这个?感觉有点像黑客?
您的方法将会起作用,但是,转换为set.
具有相同时间复杂度的另一个解决方案是:
\n\nall(i in bar for i in foo)\nRun Code Online (Sandbox Code Playgroud)\n\n这两个都有时间复杂度O(len(foo))
bar = {str(i): i for i in range(100000)}\nfoo = [str(i) for i in range(1, 10000, 2)]\n\n%timeit all(i in bar for i in foo)\n462 \xc2\xb5s \xc2\xb1 14.8 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\n\n%timeit set(foo) - set(bar)\n14.6 ms \xc2\xb1 174 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 100 loops each)\n\n# The overhead is all the difference here:\n\nfoo = set(foo)\nbar = set(bar)\n\n%timeit foo - bar\n213 \xc2\xb5s \xc2\xb1 1.48 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 1000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n\n这里的开销有很大的不同,所以我会选择all这里。