如何判断任何列表元素是否是dict的关键? 直截了当的方式是,
for i in myList:
if i in myDict:
return True
return False
但是有更快/更简洁的方式吗?
答案 0 :(得分:20)
#!python
any(x in MyDict for x in MyList)
set(MyList).intersection(MyDict)
答案 1 :(得分:6)
除了来自@Ronny's answer的any(item in my_dict for item in my_list)
:
any(map(my_dict.__contains__, my_list)) # Python 3.x
或者:
from itertools import imap
any(imap(my_dict.__contains__, my_list)) # Python 2.x
要考虑的案例:
要比较的功能(参见main.py):
def mgag_loop(myDict, myList):
for i in myList:
if i in myDict:
return True
return False
def ronny_any(myDict, myList):
return any(x in myDict for x in myList)
def ronny_set(myDict, myList):
return set(myDict) & set(myList)
def pablo_len(myDict, myList):
return len([x for x in myList if x in myDict]) > 0
def jfs_map(my_dict, my_list):
return any(map(my_dict.__contains__, my_list))
def jfs_imap(my_dict, my_list):
return any(imap(my_dict.__contains__, my_list))
结果: mgag_loop()
在所有情况下都是最快的。
def args_key_at_start(n):
'Make args for comparison functions "key at start" case.'
d, lst = args_no_key(n)
lst.insert(0, n//2)
assert (n//2) in d and lst[0] == (n//2)
return (d, lst)
def args_key_at_end(n):
'Make args for comparison functions "key at end" case.'
d, lst = args_no_key(n)
lst.append(n//2)
assert (n//2) in d and lst[-1] == (n//2)
return (d, lst)
def args_no_key(n):
'Make args for comparison functions "no key" case.'
d = dict.fromkeys(xrange(n))
lst = range(n, 2*n+1)
assert not any(x in d for x in lst)
return (d, lst)
下载main.py,make-figures.py,运行python main.py
(numpy
,matplotlib
应安装以创建图表。
要更改输入列表的最大大小,请相应地更改供应--maxn
,--npoints
的点数。例如:
$ python main.py --maxn 65536 --npoints 16
答案 2 :(得分:1)
假设您正在谈论python,另一种方法是:
return len([x for x in myList if x in myDict]) > 0
答案 3 :(得分:1)
This was a popular answer相关问题:
>>> if all (k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
您可以调整它以检查词典中是否有任何内容:
>>> if any(k in myDict for k in ("foo","bar")):
... print "Found one!"
...
Found one!
您可以查看密钥列表:
>>> if any(k in myDict for k in myList):
... print "Found one!"
...
Found one!
答案 4 :(得分:0)
非常感谢你们。我测试了所有答案的性能,最快的是
return len([x for x in myList if x in myDict]) > 0
但是我没有尝试“设定”答案,因为我没有看到如何把它变成一行。