我有一份名单。例如:
0,0,1,0,0,1
我想知道计算1 -> 0转换的最有效方法是什么。例如,在这种情况下,答案是2( 2-3和5-6位置)。
我尝试了以下几点:
stat=[0, 0, 1, 0, 0, 1, 0]
pair1=stat[:-1]
pair2=stat[1:]
result=len([i for i in zip(pair1, pair2) if i==(1,0)])我想知道是否有更好的方法
发布于 2018-04-05 20:10:41
以下是三种方法:
from itertools import islice
import numpy as np
lst = [0, 0, 1, 0, 0, 1, 0]
res1 = sum(i - j == 1 for i, j in zip(lst, lst[1:])) # 2
res2 = sum(i - j == 1 for i, j in zip(lst, islice(lst, 1, None))) # 2
res3 = np.sum(np.diff(lst) == -1) # 2解释
sum和zip来循环成对的元素。numpy库,是一种矢量化的方法。发布于 2018-04-05 20:09:54
用切片、拉链、裁剪和折叠来转换输入数据是一种方法。看看如何将这些通用操作组合起来,构建一个表示我们预期操作的机器是很棒的,即使它以迂回的方式达到了预期的结果。
然而,我认为一个更直接的方法会产生一个更自然的程序。您可以使用自然描述符和操作来表达您的意图。另一个好处是,您可以更清楚地可视化您的函数创建的过程的时空需求。Ie,下面的switches很容易在O(n)中运行;相比之下,很难估计“机器”实现的时空需求。
一个简单的递归函数
def switches (iter, last = 0):
if not iter:
return 0
first, *rest = iter
if first == last:
return switches (rest, last)
else:
return 1 + switches (rest, first)
print (switches ([ 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 ]))
# 4 :(上面的答案是4,因为它是从0到1的计数开关,从1到0的切换。你只想数一个方向的开关。我们可以这样修改我们的功能
def switches (iter, last = 0):
if not iter:
return 0
first, *rest = iter
if first == last:
return switches (rest, last)
else:
if first == 1: # only count when switching from 1
return 1 + switches (rest, first)
else:
return 0 + switches (rest, first)
print (switches ([ 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 ]))
# 2 :)但是你可以看到有一种聪明的方法来压缩条件
def switches (iter, last = 0):
if not iter:
return 0
first, *rest = iter
if first == last:
return switches (rest, last)
else:
return first + switches (rest, first)
print (switches ([ 0, 0, 1, 1, 0, 0, 1, 1, 1, 0 ]))
# 2 :)发布于 2018-04-05 20:19:36
您可以使用sum
s = [0, 0, 1, 0, 0, 1, 0]
new_s = sum(abs(s[i]-s[i+1]) == 1 for i in range(0, len(s)-1, 2))输出:
2https://stackoverflow.com/questions/49680611
复制相似问题