我有一个循环
while somecondition:
dostuff
Run Code Online (Sandbox Code Playgroud)
(对不起.很难给出一个可执行的例子,因为这是一个更大的项目的一部分).
大多数情况下,在短时间内满足条件并且循环到期.但有时候这种情况永远不会得到满足.我怎样才能最好地抓住这种情况?计时器是最好的选择吗?我怎样才能最好地实现它?
我想要一个通过值列表无限循环的生成器.
这是我的解决方案,但我可能会错过一个更明显的解决方案.
成分:一个生成器函数,用于展平无限嵌套列表,以及一个附加到自身的列表
def ge(x):
for it in x:
if isinstance(it, list):
yield from ge(it)
else:
yield(it)
def infinitecyclegenerator(l):
x = l[:]
x.append(x)
yield from ge(x)
Run Code Online (Sandbox Code Playgroud)
使用:
g = infinitecyclegenerator([1,2,3])
next(g) #1
next(g) #2
next(g) #3
next(g) #1
next(g) #2
next(g) #3
next(g) #1
...
Run Code Online (Sandbox Code Playgroud)
正如我所说的,我可能会错过一个琐碎的方式来做同样的事情,我会很乐意学习.有更简洁的方式吗?
此外,我是否应该担心内存消耗,这里有令人难以置信的无限无敌,或者我的代码是否一切都很酷?
在复杂向量的 matlab 图中将导致虚部与实部的图。
matplotlib 中是否有等效的函数?
显然这会起作用:
def plotcomplex(c, *args):
plot(real(c), imag(c), args)
Run Code Online (Sandbox Code Playgroud)
但它已经存在了吗?
我为平面中两个线段的交叉编写了一个代码测试.我不会打扰你的所有细节.
代码采用两个线段,每个线段由两个端点描述,然后通过拟合a和bin 将每个线段拟合到一条线y = a*x + b.然后它找到两条线的交点x = (b2 - b1) / (a2 - a1).最后,它测试交叉点x是否包含在两个线段中.
相关部分如下所示:
# line parameterization by a = Delta y / Delta x, b = y - a*x
a1 = (line1.edge2.y - line1.edge1.y) / (line1.edge2.x - line1.edge1.x)
b1 = line1.edge1.y - a1 * line1.edge1.x
a2 = (line2.edge2.y - line2.edge1.y) / (line2.edge2.x - line2.edge1.x)
b2 = line2.edge1.y - a2 * line2.edge1.x
# The intersection's x
x = …Run Code Online (Sandbox Code Playgroud) 我知道for在嵌套列表中理解的正确方法如下(Python 3):
lista = [[[1,2],[3],[4,5,6]],[[7],[8,9]]]
flatlista = [i for k in lista for j in k for i in j]
# results with [1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
但我的自然语言本能强烈反对.我会(错误地)期望代码是:
flatlista = [i for i in j for j in k for k in lista]
Run Code Online (Sandbox Code Playgroud)
错误的版本听起来几乎像英语,从左到右读取一个流.正确的版本需要一些嵌套的阅读技巧,左右跳过以涵盖其含义.
为什么这样的语法呢?为什么用这种方式构建语言?
我认为这in只是一个表现__contains__
In [1]: li = [1, 2, 3, 4, 5]
In [2]: 4 in li
Out[2]: True
In [3]: li.__contains__(4)
Out[3]: True
Run Code Online (Sandbox Code Playgroud)
但in速度要快2倍
In [4]: %timeit 4 in li
10000000 loops, best of 3: 103 ns per loop
In [5]: %timeit li.__contains__(4)
The slowest run took 10.06 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 213 ns per loop
Run Code Online (Sandbox Code Playgroud)
你能解释两者之间的差异in吗?为什么更快?