python-2.x

Why does comparison of bytes with str fails in Python3

眉间皱痕 提交于 2019-12-03 19:28:40
问题 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? 回答1: 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,

Elegant way to remove contiguous repeated elements in a list?

。_饼干妹妹 提交于 2019-12-03 16:47:14
I'm looking for a clean, Pythonic, way to eliminate from the following list: li = [0, 1, 2, 3, 3, 4, 3, 2, 2, 2, 1, 0, 0] all contiguous repeated elements (runs longer than one number) so as to obtain: re = [0, 1, 2, 4, 3, 1] but although I have working code, it feels un-Pythonic and I am quite sure there must be a way out there (maybe some lesser known itertools functions?) to achieve what I want in a far more concise and elegant way. Here is a version based on Karl's which doesn't requires copies of the list ( tmp , the slices, and the zipped list). izip is significantly faster than (Python

Normalizing rows of a matrix python

℡╲_俬逩灬. 提交于 2019-12-03 16:22:59
Given a 2-dimensional array in python, I would like to normalize each row with the following norms: Norm 1: L_1 Norm 2: L_2 Norm Inf: L_Inf I have started this code: from numpy import linalg as LA X = np.array([[1, 2, 3, 6], [4, 5, 6, 5], [1, 2, 5, 5], [4, 5,10,25], [5, 2,10,25]]) print X.shape x = np.array([LA.norm(v,ord=1) for v in X]) print x Output: (5, 4) # array dimension [12 20 13 44 42] # L1 on each Row How can I modify the code such that WITHOUT using LOOP, I can directly have the rows of the matrix normalized? (Given the norm values above) I tried : l1 = X.sum(axis=1) print l1 print

List minimum in Python with None?

无人久伴 提交于 2019-12-03 16:12:33
问题 Is there any clever in-built function or something that will return 1 for the min() example below? (I bet there is a solid reason for it not to return anything, but in my particular case I need it to disregard None values really bad!) >>> max([None, 1,2]) 2 >>> min([None, 1,2]) >>> 回答1: None is being returned >>> print min([None, 1,2]) None >>> None < 1 True If you want to return 1 you have to filter the None away: >>> L = [None, 1, 2] >>> min(x for x in L if x is not None) 1 回答2: using a

Unexpected Behavior of itertools.groupby

血红的双手。 提交于 2019-12-03 15:25:10
This is the observed behavior: In [4]: x = itertools.groupby(range(10), lambda x: True) In [5]: y = next(x) In [6]: next(x) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-6-5e4e57af3a97> in <module>() ----> 1 next(x) StopIteration: In [7]: y Out[7]: (True, <itertools._grouper at 0x10a672e80>) In [8]: list(y[1]) Out[8]: [9] The expected output of list(y[1]) is [0,1,2,3,4,5,6,7,8,9] What's going on here? I observed this on cpython 3.4.2 , but others have seen this with cpython 3.5 and IronPython 2.9.9a0

How to pass arguments to the metaclass from the class definition?

☆樱花仙子☆ 提交于 2019-12-03 15:17:35
问题 I'm trying to dynamically generate classes in python 2.7, and am wondering if you can easily pass arguments to the metaclass from the class object. I've read this post, which is awesome, but doesn't quite answer the question. at the moment I am doing: def class_factory(args, to, meta_class): Class MyMetaClass(type): def __new__(cls, class_name, parents, attrs): attrs['args'] = args attrs['to'] = to attrs['eggs'] = meta_class class MyClass(object): metaclass = MyMetaClass ... but this requires

Use of input/raw_input in python 2 and 3 [duplicate]

和自甴很熟 提交于 2019-12-03 14:24:50
问题 This question already has answers here : Backwards-compatible input calls in Python (4 answers) Closed last year . I would like to set a user prompt with the following question: save_flag is not set to 1; data will not be saved. Press enter to continue. input() works in python3 but not python2. raw_input() works in python2 but not python3. Is there a way to do this so that the code is compatible with both python 2 and python 3? 回答1: Bind raw_input to input in Python 2: try: input = raw_input

Where does Python store the name binding of function closure?

天涯浪子 提交于 2019-12-03 13:26:52
So recently I understand the concept of function closure. def outer(): somevar = [] assert "somevar" in locals() and not "somevar" in globals() def inner(): assert "somevar" in locals() and not "somevar" in globals() somevar.append(5) return somevar return inner function = outer() somevar_returned = function() assert id(somevar_returned) == id(function.func_closure[0].cell_contents) As much as I understand, the objective of function closure is to keep an active reference to the object, in order to avoid garbage collection of this object. This is why the following works fine : del outer somevar

Buffers and Memoryview Objects explained for the non-C programmer

可紊 提交于 2019-12-03 12:58:15
Python 2.7 has introduced a new API for buffers and memoryview objects . I read the documentation on them and I think I got the basic concept (accessing the internal data of an object in a raw form without copying it, which I suppose means a "faster and less memory-hungry" way to get object data), but to really understand the documentation, the reader should have a knowledge of C that is beyond the one I have. I would be very grateful if somebody would take the time to: explain buffers and memoryview objects in "layman terms" and describe a scenario in which using buffers and memoryview

Identifying that a variable is a new-style class in Python?

我们两清 提交于 2019-12-03 11:48:46
问题 I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out. import types class oldclass: pass def test(): o = oldclass() if type(o) is types.InstanceType: print 'Is old-style' else: print 'Is NOT old-style' But I haven't been able to find anything that works for new-style classes. I found this question, but the proposed solutions don't seem to work as expected, because