[英]in a loop, only add to a dictionary or list or tuple if doesn't contains the key
I am looping in python and want to add a key to a dictionary only if it isn't already in the collection. 我在python中循环,并且仅当字典中没有键时才想将键添加到字典中。
How can I do this? 我怎样才能做到这一点?
mydic = {}
for x in range(100):
??
For a dict, it's easy and fast: 对于一个字典,它是简单而快速的:
for x in range(100):
if x not in mydic:
mydic[x] = x # or whatever value you want
that is, just check with not in
instead of in
. 也就是说,只需使用
not in
而不是in
检查。
This is great for a dict. 这对于字典来说是很棒的。 For a list, it's going to be extremely slow (quadratic);
对于列表,它将非常慢(二次); for speed, you need to add an auxiliary set (hopefully all items in the list are hashable) before the loop, and check and update it in the loop.
为了提高速度,您需要在循环之前添加一个辅助集(希望列表中的所有项目都是可哈希的),然后在循环中检查并更新它。 Ie:
即:
auxset = set(mylist)
for x in range(100):
if x not in auxset:
auxset.add(x)
mylist.append(x) # or whatever
For a tuple, it's impossible to add anything to it, or in any other way modify it, of course: tuples are immutable! 对于元组,当然不能向其中添加任何内容,也不能以任何其他方式对其进行修改:元组是不可变的! Surely you know that?!
你当然知道吗? So, why ask?
那么,为什么要问?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.