我试图了解引擎盖下的python哈希函数.我创建了一个自定义类,其中所有实例都返回相同的哈希值.
class C(object):
def __hash__(self):
return 42
Run Code Online (Sandbox Code Playgroud)
我只是假设上面的类中只有一个实例可以随时出现在一个集合中,但实际上一个集合可以有多个具有相同散列的元素.
c, d = C(), C()
x = {c: 'c', d: 'd'}
print x
# {<__main__.C object at 0x83e98cc>:'c', <__main__.C object at 0x83e98ec>:'d'}
# note that the dict has 2 elements
Run Code Online (Sandbox Code Playgroud)
我进行了一些实验,发现如果我重写__eq__
方法使得类的所有实例比较相等,那么该集只允许一个实例.
class D(C):
def __eq__(self, other):
return hash(self) == hash(other)
p, q = D(), D()
y = {p:'p', q:'q'}
print y
# {<__main__.D object at 0x8817acc>]: 'q'}
# note that the dict has only 1 element
Run Code Online (Sandbox Code Playgroud)
所以我很想知道dict有多个具有相同哈希的元素.谢谢!
注意:编辑问题以给出dict(而不是set)的例子,因为答案中的所有讨论都是关于dicts的.但这同样适用于集合; 集合也可以有多个具有相同散列值的元素.
我有一个元组列表,每个元组都是一个元组(start-time, end-time)
.我正在尝试合并所有重叠的时间范围并返回不同时间范围的列表.例如
[(1, 5), (2, 4), (3, 6)] ---> [(1,6)]
[(1, 3), (2, 4), (5, 8)] ---> [(1, 4), (5,8)]
Run Code Online (Sandbox Code Playgroud)
这是我实现它的方式.
# Algorithm
# initialranges: [(a,b), (c,d), (e,f), ...]
# First we sort each tuple then whole list.
# This will ensure that a<b, c<d, e<f ... and a < c < e ...
# BUT the order of b, d, f ... is still random
# Now we have only 3 possibilities
#================================================
# b<c<d: a-------b Ans: …
Run Code Online (Sandbox Code Playgroud) 在ThreadPoolExecutor(TPE)中,回调始终保证在与提交的函数相同的线程中运行吗?
例如,我使用以下代码对此进行了测试.我跑了很多次,它似乎func
并callback
始终在同一个线程跑.
import concurrent.futures
import random
import threading
import time
executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
def func(x):
time.sleep(random.random())
return threading.current_thread().name
def callback(future):
time.sleep(random.random())
x = future.result()
cur_thread = threading.current_thread().name
if (cur_thread != x):
print(cur_thread, x)
print('main thread: %s' % threading.current_thread())
for i in range(10000):
future = executor.submit(func, i)
future.add_done_callback(callback)
Run Code Online (Sandbox Code Playgroud)
但是,当我删除time.sleep(random.random())
语句时,它似乎失败了,即至少有几个func
函数并且callbacks
没有在同一个线程中运行.
对于我正在处理的项目,回调必须始终与提交的函数在同一个线程上运行,所以我想确保这是由TPE保证的.(而且没有随机睡眠的测试结果似乎令人费解).
考虑一下Python中策略模式的这个例子(改编自这里的例子).在这种情况下,替代策略是一种功能.
class StrategyExample(object):
def __init__(self, strategy=None) :
if strategy:
self.execute = strategy
def execute(*args):
# I know that the first argument for a method
# must be 'self'. This is just for the sake of
# demonstration
print locals()
#alternate strategy is a function
def alt_strategy(*args):
print locals()
Run Code Online (Sandbox Code Playgroud)
以下是默认策略的结果.
>>> s0 = StrategyExample()
>>> print s0
<__main__.StrategyExample object at 0x100460d90>
>>> s0.execute()
{'args': (<__main__.StrategyExample object at 0x100460d90>,)}
Run Code Online (Sandbox Code Playgroud)
在上面的例子中s0.execute
是一个方法(不是普通的vanilla函数),因此args
,正如预期的那样,第一个参数是self
.
以下是替代策略的结果.
>>> s1 = …
Run Code Online (Sandbox Code Playgroud) 当我在阅读像Python一样的代码: David Goodger 的惯用Python时,我偶然发现了以下警告.
摘自文章......
Run Code Online (Sandbox Code Playgroud)print('Hello %(name)s, you have %(messages)i messages' % locals())
这非常强大.这样,您可以执行所需的所有字符串格式设置,而无需担心插值值与模板的匹配.
但是权力可能是危险的."拥有权利的同时也被赋予了重大的责任." 如果将
locals()
from与外部提供的模板字符串一起使用,则将 整个本地名称空间公开给调用者.这只是要记住的事情.
我试图了解使用可能是危险的具体情况locals()
.locals()
可以理解如何利用代码中存在的任何示例.谢谢!
有没有更简洁的方式来写这个?
f(a=a, b=b, c=c, d=d, e=e)
Run Code Online (Sandbox Code Playgroud)
背景:我有一个参数太多的函数
f(a, b, c, d, e):
pass
Run Code Online (Sandbox Code Playgroud)
我的程序我有局部变量,其名称与函数参数完全相同.
a, b, c, d, e = range(5)
Run Code Online (Sandbox Code Playgroud)
我想用关键字参数调用该函数.由于变量的名称相同,因此调用的外观如此.
g = f(a=a, b=b, c=c, d=d, e=e) # this can get very long
Run Code Online (Sandbox Code Playgroud)
当然,我可以使用位置而不是像这样的关键字来传递结果
g = f(a, b, c, d, e)
Run Code Online (Sandbox Code Playgroud)
但是a
,b
,c
,d
,e
是在这个例子中的变量只是名字,很容易看到正确的顺序.然而不幸的是,我的程序中的变量被命名为更复杂,并且没有容易辨别的自然顺序.所以我真的想通过关键字传递它们以避免任何错误.
我需要在元组列表中找到n个最大的元素.这是前3个元素的示例.
# I have a list of tuples of the form (category-1, category-2, value)
# For each category-1, ***values are already sorted descending by default***
# The list can potentially be approximately a million elements long.
lot = [('a', 'x1', 10), ('a', 'x2', 9), ('a', 'x3', 9),
('a', 'x4', 8), ('a', 'x5', 8), ('a', 'x6', 7),
('b', 'x1', 10), ('b', 'x2', 9), ('b', 'x3', 8),
('b', 'x4', 7), ('b', 'x5', 6), ('b', 'x6', 5)]
# This is what I need. …
Run Code Online (Sandbox Code Playgroud) 如何将不可变对象的名称重新绑定到扩充赋值的结果?
对于可变对象,例如,if x = [1, 2, 3]
和y = [4,5],那么当我们执行x + = y时,它会被执行,因为x.__iadd__(y)
它会x
在适当的位置进行修改,并且名称x
会再次重新绑定到它吗?
当它x
是不可变的时,它是如何工作的?以下是Python文档对扩充分配的看法.
如果x是一个没有定义
__iadd__()
方法的类的实例,x.__add__(y)
并且y.__radd__(x)
被考虑,就像评估一样x + y
.
OK,现在如果x = (1, 2, 3)
和y = (4, 5)
当我们这样做x += y
,蟒蛇执行x.__add__(y)
这将创建一个新的对象.但是,当这又如何新对象获得反弹到x
?
我去的CPython特别是源代码洞穴探险tuple
对象(tupleobject.c)和AugAssign
部分在Python的ast.c和ast.c,但不能真正了解重新绑定是如何发生的.
编辑:删除原始问题中的误解,并将其更改为问题形式,以防止混淆未来的读者.
我有一个问题,我希望有一个嵌套的for循环连接一个字符串.由于某种原因,我没有得到正确的输出.有人可以给我一些建议吗?这应该很简单.
newRow = []
matrix = []
for i in range(0,3):
for j in range(0,5):
newRow.append(j)
matrix.append(newRow)
print matrix
python test.py
[[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]]
Run Code Online (Sandbox Code Playgroud)
我想要它打印...
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, …
Run Code Online (Sandbox Code Playgroud)