Check if a given key already exists in a dictionary

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: if 'key1' in dict.keys(): print "blah" else: print "boo" I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary? in is the intended way to test for the existence of a key in a dict . d = dict() for i in xrange(

检查给定的密钥是否已经存在于字典中

我想在更新密钥的值之前测试字典中是否存在密钥。 我写了下面的代码: if 'key1' in dict.keys(): print "blah" else: print "boo" 我认为这不是完成这项任务的最好方法。 有没有更好的方法来测试字典中的键? in是用于测试dict是否存在密钥的预期方式。 d = dict() for i in xrange(100): key = i % 10 if key in d: d[key] += 1 else: d[key] = 1 如果你想要一个默认值,你总是可以

"Least Astonishment" and the Mutable Default Argument

Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue: def foo(a=[]): a.append(5) return a Python novices would expect this function to always return a list with only one element: [5] . The result is instead very different, and very astonishing (for a novice): >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] &g

“最小的惊讶”和可变的默认参数

任何人用Python修补足够长的时间都被以下问题困扰(或被撕碎): def foo(a=[]): a.append(5) return a Python新手会期望这个函数总是返回一个只有一个元素的列表: [5] 。 结果是非常不同的,而且非常惊人(对于新手来说): >>> foo() [5] >>> foo() [5, 5] >>> foo() [5, 5, 5] >>> foo() [5, 5, 5, 5] >>> foo() 我的一位经理曾经第一次遇到这个功能,并称这是该

Difference between

Python __str__和__repr__什么区别? Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex's post: The default implementation is useless (it's hard to think of one which wouldn't be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container's __str__ uses contained objects' __repr__ Defa

之间的区别

Python __str__和__repr__什么区别? 亚历克斯总结得很好,但令人惊讶的是,它太简洁了。 首先,让我重申Alex的帖子中的主要观点: 默认的实现是无用的(很难想象一个不会的,但是是的) __repr__目标是明确的 __str__目标是可读的 容器的__str__使用包含的对象' __repr__ 默认实现是无用的 这大部分是令人惊讶的,因为Python的默认值相当有用。 但是,在这种情况下,具有__repr__的默认值,其行为如下: re

Finding the index of an item given a list containing it in Python

对于列表["foo", "bar", "baz"]和列表"bar"的项目,在Python中获取索引(1)的最简单方法是什么? >>> ["foo", "bar", "baz"].index("bar") 1 参考:数据结构>更多关于列表 One thing that is really helpful in learning Python is to use the interactive help function: >>> help(["foo", "bar", "baz"]) Help on list object: class list(object) ... | |

查找包含Python的列表中的项目索引

对于列表["foo", "bar", "baz"]和列表"bar"的项目,在Python中获取索引(1)的最简单方法是什么? >>> ["foo", "bar", "baz"].index("bar") 1 参考:数据结构>更多关于列表 有一点对学习Python非常有帮助,那就是使用交互式帮助功能: >>> help(["foo", "bar", "baz"]) Help on list object: class list(object) ... | | index(...) | L.index(value,

Understanding Python's slice notation

I need a good explanation (references are a plus) on Python's slice notation. To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it. It's pretty simple really: a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:

了解Python的切片符号

我需要一个很好的解释(引用是加号)Python的切片符号。 对我而言,这个表示法需要一点点提升。 它看起来非常强大,但我还没有完全摆脱困境。 这真的很简单: a[start:end] # items start through end-1 a[start:] # items start through the rest of the array a[:end] # items from the beginning through end-1 a[:] # a copy of the whole array 也有step值,可以用于以上任何一个: a[start:end:st

How do I install pip on Windows?

pip is a replacement for easy_install . But should I install pip using easy_install on Windows? Is there a better way? Python 2.7.9+ and 3.4+ Good news! Python 3.4 (released March 2014) and Python 2.7.9 (released December 2014) ship with Pip. This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer exc

我如何在Windows上安装点子?

pip是easy_install的替代品。 但是,我应该在Windows上使用easy_install安装pip吗? 有没有更好的办法? Python 2.7.9 +和3.4+ 好消息! Python 3.4(2014年3月发布)和Python 2.7.9(2014年12月发布)与Pip一起发布。 这是任何Python版本的最佳功能。 它使每个人都可以访问社区的丰富图书馆。 由于安装难度大,新手不再被排除在社区图书馆之外。 在与包管理员一起交付时,Python加入了Ruby,Node.js,Haskell,Perl

Accessing the index in 'for' loops?

How do I access the index itself for a list like the following? ints = [8, 23, 45, 12, 78] When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case? Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic. The better option is to use the built-in function e

访问'for'循环中的索引?

如何访问索引本身的列表如下所示? ints = [8, 23, 45, 12, 78] 当我使用for循环遍历它时,如何访问循环索引,在这种情况下从1到5? 使用额外的状态变量,如索引变量(通常用于C或PHP等语言中),被认为是非pythonic。 更好的选择是使用Python 2和3中提供的内置函数enumerate() : for idx, val in enumerate(ints): print(idx, val) 查看更多PEP 279。 使用for循环,在这种情况下,我如何访问循环索引,从1到5?

Using global variables in a function other than the one that created them

If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access? You can use a global variable in other functions by declaring it as global in each function that assigns to it: globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global

在创建它们的函数中使用全局变量

如果我在一个函数中创建一个全局变量,如何在另一个函数中使用该变量? 我是否需要将全局变量存储在需要访问的函数的局部变量中? 您可以通过声明为使用其他功能的全局变量, global在分配给它的每个功能: globvar = 0 def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1 def print_globvar(): print(globvar) # No need for global declaration to re

How to make a chain of function decorators?

How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return "Hello" ...which should return: "<b><i>Hello</i></b>" I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works. Check out the documentation to see how decorators work. Here is wh

如何创建一个函数装饰器链?

我如何在Python中创建两个可以执行以下操作的装饰器? @makebold @makeitalic def say(): return "Hello" ...应该返回: "<b><i>Hello</i></b>" 我并没有试图在真正的应用程序中这样制作HTML ,只是试图理解装饰器和装饰器链接是如何工作的。 查看文档以查看装饰器的工作原理。 以下是您要求的内容: def makebold(fn): def wrapped(): return "<b>" + fn() + "</b>"

Difference between append vs. extend list methods in Python

列表方法append()和extend()之间有什么区别? append : Appends object at end. x = [1, 2, 3] x.append([4, 5]) print (x) gives you: [1, 2, 3, [4, 5]] extend : Extends list by appending elements from the iterable. x = [1, 2, 3] x.extend([4, 5]) print (x) gives you: [1, 2, 3, 4, 5] append adds an element to a list, extend concatenates the first list with another list (or another iterable, not ne

Python中append和extend列表方法的区别

列表方法append()和extend()之间有什么区别? append :在最后追加对象。 x = [1, 2, 3] x.append([4, 5]) print (x) 给你: [1, 2, 3, [4, 5]] extend :通过追加迭代中的元素来扩展列表。 x = [1, 2, 3] x.extend([4, 5]) print (x) 给你: [1, 2, 3, 4, 5] append将一个元素添加到列表中, extend第一个列表与另一个列表(或另一个可迭代的,不一定是列表)连接起来。 >>> li = ['a', 'b', 'mpilgrim', 'z',