首页 > 解决方案 > Python:获取对之间的距离

问题描述

在我们的数据集中,我们有大量的序列,例如“aismeorisityou”,我们希望得到两个相邻对之间的距离。所以在这种情况下,在两个 'is' 之间还有 6 个其他字母。解决这个问题的最佳方法是什么?

这是我们所得到的..

count = 0
for i in range(1, len(x)):
    if x[i] == x[i-1]:
        # True if there are pairs - now count the distance
return None

输出应该是距离,6。

标签: python

解决方案


您将需要第二个内部循环:

x= 'aismeorisityou'
for i in range(1, len(x)):
    for j in range(i+1, len(x)-1):
        if x[i] == x[j] and x[i+1]==x[j+1]:
            print(x[i]+x[i+1])
            print('separated by: ' + str(j-i))

返回:

is
separated by: 6

我希望它有帮助!


推荐阅读