Python

Is there a python convention for when you should implement __str__() versus __unicode__() . I've seen classes override __unicode__() more frequently than __str__() but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice to implement both? __str__() is the old method -- it returns bytes. __uni

蟒蛇

有什么时候应该实现__str__()和__unicode__()的Python约定。 我发现__unicode__() __str__() __unicode__()更频繁地覆盖__unicode__() __str__()但它看起来并不一致。 是否有更好的实施方法和其他方法的具体规则? 是否有必要/好的做法来实现两者? __str__()是旧方法 - 它返回字节。 __unicode__()是新的首选方法 - 它返回字符。 这些名称有点令人困惑,但在2.x中,出于兼容性原因,我们坚持使用它们。 通常,您应该将

How to count the occurrences of a list item?

给定一个项目,我如何计算它在Python中的列表中的出现次数? If you only want one item's count, use the count method: >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3 Don't use this if you want to count multiple items. Calling count in a loop requires a separate pass over the list for every count call, which can be catastrophic for performance. If you want to count all items, or even just mu

如何统计列表项的出现次数?

给定一个项目,我如何计算它在Python中的列表中的出现次数? 如果您只需要一个项目的计数,请使用count方法: >>> [1, 2, 3, 4, 1, 4, 1].count(1) 3 如果要计算多个项目,请不要使用此项。 在循环中调用count需要在每次count调用时对列表进行单独传递,这可能对性能造成灾难性影响。 如果您想要计算所有项目,或者甚至只计算多个项目,请使用Counter ,如其他答案中所述。 如果您使用的是Python 2.7或3,并且您希

How to randomly select an item from a list?

Assume I have the following list: foo = ['a', 'b', 'c', 'd', 'e'] What is the simplest way to retrieve an item at random from this list? Use random.choice : import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) For cryptographically secure random choices (eg for generating a passphrase from a wordlist), use random.SystemRandom class: import random foo = ['battery', 'cor

如何从列表中随机选择一个项目?

假设我有以下列表: foo = ['a', 'b', 'c', 'd', 'e'] 从这个列表中随机检索一个项目的最简单方法是什么? 使用random.choice : import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo)) 对于加密安全的随机选择(例如,用于从单词列表生成密码短语),请使用random.SystemRandom类: import random foo = ['battery', 'correct', 'horse', 'staple'] secure_random = random.SystemRandom() print(s

What is the best way to compare floats for almost

It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues. For example: https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ What is the recommended way to deal with this in Python? Surely there is a standard library function for this somewhere? Python 3.5 adds the math.isclose and cmath.isclose fu

几乎可以比较花车的最佳方式是什么?

众所周知,由于四舍五入和精确性问题,比较花车平等是有点费劲。 例如:https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ 在Python中处理这个问题的建议方法是什么? 这个地方肯定有一个标准的库函数? Python 3.5添加了PEP 485中描述的math.isclose和cmath.isclose函数。 如果您使用的是早期版本的Python,则在文档中给出等效函数。 def isclose(a, b, rel_tol=1e-09,

Python's in

Do you have a good reference on Python's class in-built function? To me, this function needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head around it and am looking for a good guide. i am speaking about this: class squash(): def __init___(self, chocolate) i just don't understand them In Python class is not a built-in function, it is a com

Python的英寸

你对Python的类内置函数有很好的参考吗? 对我而言,这个功能需要一点点提升。 它看起来非常强大,但我还没有完全理解它,并且正在寻找一个好的指导。 我正在谈论这个问题: class squash(): def __init___(self, chocolate) 我只是不明白他们 在Python中, class不是内置函数,它是用于创建类的复合语句。 这在文档中描述在以下位置: https://docs.python.org/2/reference/compound_stmts.html#class-definitio

if/else in Python's list comprehension?

How can I do the following in Python? row = [unicode(x.strip()) for x in row if x is not None else ''] Essentially: replace all the Nones with empty strings, and then carry out a function. You can totally do that, it's just an ordering issue: [ unicode(x.strip()) if x is not None else '' for x in row ] Note that this actually uses a different language construct, a conditional expres

if / else在Python的列表理解?

我如何在Python中执行以下操作? row = [unicode(x.strip()) for x in row if x is not None else ''] 主要有: 用空字符串替换所有的Nones,然后 执行功能。 你完全可以这么做,这只是一个订购问题: [ unicode(x.strip()) if x is not None else '' for x in row ] 注意,这实际上使用不同的语言结构,有条件的表达,这本身是不是理解语法的一部分,而if之后for…in是列表内涵的一部分,用来过滤从源头迭代元素。

Peak detection in a 2D array

I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions. I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an example of one paw, where I used Excel to draw the areas I want to 

二维阵列中的峰值检测

我正在帮助兽医诊所测量狗爪下的压力。 我使用Python进行数据分析,现在我试图将爪子分成(解剖)子区域。 我制作了每个爪子的二维数组,每个爪子随着时间的推移装载了每个传感器的最大值。 这里有一个爪子的例子,我用Excel绘制了我想检测的区域。 这些传感器周围有2 x 2个盒子,带有当地最大值,总和最大。 所以我尝试了一些实验,并决定简单地查找每列和每行的最大值(由于爪子的形状,不能看向一个方向)。 这似乎能

How does Python's super() work with multiple inheritance?

I'm pretty much new in Python object oriented programming and I have trouble understanding the super() function (new style classes) especially when it comes to multiple inheritance. For example if you have something like: class First(object): def __init__(self): print "first" class Second(object): def __init__(self): print "second" class Third(First, Second):

Python的super()如何处理多重继承?

我在Python面向对象编程方面非常新颖,并且我很难理解super()函数(新样式类),特别是在涉及多重继承时。 例如,如果你有类似的东西: class First(object): def __init__(self): print "first" class Second(object): def __init__(self): print "second" class Third(First, Second): def __init__(self): super(Third, self).__init__() print "that's it" 我没有得到的

Python's equivalent of && (logical

Here's my code: # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form # a-front + b-front + a-back + b-back def front_

Python的等同于&&(逻辑

这是我的代码: # F. front_back # Consider dividing a string into two halves. # If the length is even, the front and back halves are the same length. # If the length is odd, we'll say that the extra char goes in the front half. # e.g. 'abcde', the front half is 'abc', the back half 'de'. # Given 2 strings, a and b, return a string of the form # a-front + b-front + a-back + b-back def front_back(

Understanding kwargs in Python

What are the uses for **kwargs in Python? I know you can do an objects.filter on a table and pass in a **kwargs argument. Can I also do this for specifying time deltas ie timedelta(hours = time1) ? How exactly does it work? Is it classes as 'unpacking'? Like a,b=1,2 ? You can use **kwargs to let your functions take an arbitrary number of keyword arguments ("kwargs" mea

在Python中理解kwargs

Python中的**kwargs什么用途? 我知道你可以在一张桌子上做一个objects.filter并传入一个**kwargs参数。 我也可以这样做,用于指定时间delta,即timedelta(hours = time1) ? 它究竟如何工作? 它被称为“解包”吗? 像a,b=1,2一样a,b=1,2 ? 您可以使用**kwargs让您的函数获取任意数量的关键字参数(“kwargs”表示“关键字参数”): >>> def print_keyword_args(**kwargs): ... # kwargs is a dict of the k