python-2.x

dicts are not orderable in python 3?

不羁岁月 提交于 2019-11-30 17:03:08
问题 Why are dicts orderable in python2, but not in python3? I can't find it anywhere in the documentation. Python 3.3.4 (default, Feb 11 2014, 16:14:21) >>> sorted([{'a':'a'},{'b':'b'}]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: dict() < dict() vs. Python 2.7.6 (default, Feb 26 2014, 12:01:28) >>> sorted([{'a':'a'},{'b':'b'}]) [{'a': 'a'}, {'b': 'b'} 回答1: Python 2 uses an undocumented ordering, implemented as a .__cmp__() special method.

one-liner reduce in Python3

南楼画角 提交于 2019-11-30 16:45:39
In Python3, I am looking for a way to compute in one line a lambda function called on elements two by two. Let’s say I want to compute the LCM of a list of integers, this can be done in one line in Python2 : print reduce(lambda a,b: a * b // gcd(a, b), mylist) Is it possible to do the same in one line Python3 (implied, without functools.reduce )? In Python3 I know that filter , map and reduce are gone. I don’t feel I need filter and map anymore because they can be written in Python3 in a shorter and more clear fashion but I thought I could find a nice replacement for reduce as well, except I

Is there a convenient way to apply a lookup table to a large array in numpy?

孤街浪徒 提交于 2019-11-30 16:26:28
问题 I’ve got an image read into numpy with quite a few pixels in my resulting array. I calculated a lookup table with 256 values. Now I want to do the following: for i in image.rows: for j in image.cols: mapped_image[i,j] = lut[image[i,j]] Yep, that’s basically what a lut does. Only problem is: I want to do it efficient and calling that loop in python will have me waiting for some seconds for it to finish. I know of numpy.vectorize() , it’s simply a convenience function that calls the same python

How do I check if a user left the 'input' or 'raw_input' prompt empty?

旧街凉风 提交于 2019-11-30 15:15:34
问题 How do I check if input has been entered? For example: x = str(raw_input('Message>> ')) or y = input('Number>> ') 回答1: You know if nothing was entered for the second one because it will raise a SyntaxError . You can catch the error like this: try: y=input('Number>> ') except SyntaxError: y = None then test # not just 'if y:' because 0 evaluates to False! if y is None: or, preferably, use raw_input : try: y = int(raw_input('Number>> ')) except ValueError: print "That wasn't a number!" For the

Python 2.x multiple version issues regarding PYTHONPATH

ⅰ亾dé卋堺 提交于 2019-11-30 14:39:43
There's Python 2.6 installed in the system. Now I want to use modules introduced in Python 2.7. Because I have no root privilege, I have built & installed 2.7 under my home directory ($HOME/local/) I added the following to my $HOME/.bashrc: export PATH=$HOME/local/bin:$PATH export PYTHONPATH=$HOME/local/lib/python2.7:$PYTHONPATH Now I encountered the two problems I want ask for workarounds. 1. Invoking Python 2.7 Newly installed Python 2.7 doesn't find 2.6 modules in system's library path (/usr/lib/python2.6/site-packages/). Should I add it to PYTHONPATH manually? Is there any nicer solution?

How do I check if a user left the 'input' or 'raw_input' prompt empty?

回眸只為那壹抹淺笑 提交于 2019-11-30 14:03:29
How do I check if input has been entered? For example: x = str(raw_input('Message>> ')) or y = input('Number>> ') You know if nothing was entered for the second one because it will raise a SyntaxError . You can catch the error like this: try: y=input('Number>> ') except SyntaxError: y = None then test # not just 'if y:' because 0 evaluates to False! if y is None: or, preferably, use raw_input : try: y = int(raw_input('Number>> ')) except ValueError: print "That wasn't a number!" For the first one, x will be an empty string if nothing is entered. The call to str is unnecessary -- raw_input

How to write Python 2.x as much compatible with Python 3.x as possible?

流过昼夜 提交于 2019-11-30 10:15:26
问题 There are many ways to include Python 3.x features in Python 2.x , so code of Python 2.x scripts could be easily converted into Python 3.x in the future. One of these examples is replacing print statement with print() function: >>> from __future__ import print_function Is there any list or resource that could give one some ideas how to make Python 2.x code as close to Python 3.x as possible? Could you give examples of other useful imports or definitions that can make Python 2.x look and

Valid syntax in both Python 2.x and 3.x for raising exception?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 09:17:47
How can I port this code to Python 3 so that it would run in both, Python 2 and Python3? raise BarException, BarException(e), sys.exc_info()[2] (copied from http://blog.ionelmc.ro/2014/08/03/the-most-underrated-feature-in-python-3/ ) Bonus question Does it make sense to do something like IS_PYTHON2 = sys.version_info < (3, 0) if IS_PYTHON2: raise BarException, BarException(e), sys.exc_info()[2] # replace with the code that would run in Python 2 and Python 3 respectively else: raise BarException("Bar is closed on Christmas") You'll have to resort to using exec() because you cannot use the 3

How can I combine range() functions

冷暖自知 提交于 2019-11-30 09:15:02
问题 For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is a = range(1,6) b = range(7,31) for i in a+b: print i Is there a way to do it more efficiently? 回答1: In python 2 you are not combining "range functions"; these are just lists. Your example works just well. But range always creates a full list in memory, so a better way if only needed in for loop could be to to use a generator expression and xrange: range_with_holes = (j for j in xrange(1, 31) if j != 6)

Why does comparison of bytes with str fails in Python3

时光总嘲笑我的痴心妄想 提交于 2019-11-30 08:28:49
In Python3 this expression evaluates as False : b"" == "" while in Python2 this comparison is True : u"" == "" Checking for identity with is obviously fails in both cases. But why would they implement such a behaviour in Python3? In Python 2.x, the design goal for unicode is to enable transparent operations between unicode & byte strings by implicitly converting between the 2 types. When you do the comparison u"" == "" , the unicode LHS is automatically encoded into a byte string first, and then compared to the str RHS. That's why it returned True . In contrast, Python 3.x, having learned from