用Python方式计算列表中特定邻居的方法 [英] Pythonic way to count specific neighbors in a list

查看:129
本文介绍了用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

说明

  1. 第一种方法利用sum和一个生成表达式以及zip来循环成对元素.
  2. 第二种方法与第一种方法相似,但性能更好,因为它避免显式构建第二种列表.
  3. 第三种方法利用了第三方numpy库,是一种矢量化方法.
  1. First method utilises sum with a generation expression and zip to loop pairwise elements.
  2. Second method is similar to the first but performs better as it avoids building a second list explicitly.
  3. Third method utilises the 3rd party numpy library and is a vectorised approach.

这篇关于用Python方式计算列表中特定邻居的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆