[英]What is good way to check a key of a dictionary in python?
I have a loop that over some values. 我有一些值的循环。 I have a dictionary that it's keys are in the values of the loop iteration.
我有一本字典,它的键在循环迭代的值中。
I can't change the outer loop. 我无法更改外循环。
for i in range(1, 1000000000000):
if i in my_dict.keys():
func()
other_func(i)
Each element in: my_dict.keys()
appears in range(1, 1000000000000)
. my_dict.keys()
中的每个元素都出现在range(1, 1000000000000)
my_dict.keys()
range(1, 1000000000000)
。 However the number of elements in my_dict.keys()
is much smaller than the number of iterations. 但是,
my_dict.keys()
的元素数比迭代数小得多。
The problem is that each if check is time consuming. 问题是每次检查都非常耗时。 What is a good way of handling this?
有什么好的处理方法?
I think you can do something like this: 我认为您可以执行以下操作:
for i in my_dict:
if 0 < i < 1000000000000:
func()
range(1, 1000000000000)
will generate a list of numbers from 1
to 999999999999
and you just need to check if your key is in that range. range(1, 1000000000000)
将生成一个从1
到999999999999
的数字列表,您只需要检查您的密钥是否在该范围内即可。 So you don't really need to generate the list using range
itself. 因此,您实际上并不需要使用
range
本身来生成列表。
Change your for loop. 更改您的for循环。 See below script.
参见以下脚本。
for key in my_dict.keys():
if 0 < int(key) < 1000000000000:
func()
Change for loop because in original implementation for loop would iterate at most 1000000000000 times. 更改for循环,因为在原始实现中,for循环最多重复1000000000000次。 But now it will iterate maximum of length of my_dict.
但是现在它将迭代my_dict的最大长度。
Well, try
and except
is a good way to go. 好吧,
try
和except
是一个不错的选择。
for i in range(1, 100000000):
try:
my_dict[i]
except KeyError:
continue
func()
If i
is not in the keys
, then it will throw KeyError
and will go to the next iteration. 如果
i
不在keys
,那么它将抛出KeyError
并进入下一个迭代。 If i
is proper key
then the func()
will be called. 如果
i
是正确的key
则将func()
。
The most simplest way is , 最简单的方法是
if my_dict.has_key('key'): 如果my_dict.has_key('key'):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.