用Python方式计算列表中特定邻居的方法 [英] Pythonic way to count specific neighbors in a list
本文介绍了用Python方式计算列表中特定邻居的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个清单.例如:
[0,0,1,0,0,1,0]
[0, 0, 1, 0, 0, 1, 0]
我想知道计算 1-> 0 转换的最有效方法是什么.例如,在这种情况下,答案是2(在2-3和5-6位置)
I'd like to know what is the most effective way to count the 1 -> 0 transitions. In this case for example the answer is 2 (in the 2-3 and in the 5-6 positions)
我尝试了以下操作:
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)])
我想知道是否有更好的方法
I'm wondering if there is a better way
推荐答案
有3种方法:
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
库,是一种矢量化方法.
- First method utilises
sum
with a generation expression andzip
to loop pairwise elements. - Second method is similar to the first but performs better as it avoids building a second list explicitly.
- Third method utilises the 3rd party
numpy
library and is a vectorised approach.
这篇关于用Python方式计算列表中特定邻居的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文