Python过滤/比较序列中的每秒值

时间:2011-10-13 15:12:01

标签: python filter

  

可能重复:
  How to make a function that counts how many times each element is equal to 2 elements to its right

我需要以下提示的帮助。由于某种原因,我继续得到一个“'int'对象是不可订阅的”errpr,并不知道如何解决它。我觉得它与我的助手功能有关。

以下是测试:

         '''
             skip(X) counts how many times an item in 
             sequence X is equal to the item 
             "two places to the right" in X.

         Examples:

             skip("evening") is 2, once
                         for 'e' and once for 'n'   
             skipt([1,2,3,4]) is 0 
             skipt([0,0,0,0,0]) is 3, because
                         there are five 0's, but 
                         the last two can't be 
                         compared to item two places
                         to the right. 

>>> X = "onoratitatio" 
>>> skip(X)
3
>>> Y = 2*[3,1]+4*[1,5] 
>>> skip(Y)
8
>>> skip([5])
0
'''

以下是我目前创建的内容:

def helper(X):
    return X[0] == X[2]

def skip(X):
    return len(filter(helper,X))

我真的不知道,但我已经厌倦了这个问题。有没有人有任何想法?

2 个答案:

答案 0 :(得分:0)

In [4]: word = "mississippi"    
In [5]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]
In [6]: print len(word_list)
1

In [7]: word = "evening"
In [8]: word_list = [w for w in xrange(len(word) - 2) if word[w] == word[w + 2]]
In [9]: print len(word_list)
2

答案 1 :(得分:0)

您不能使用filter()执行此操作,因为filter从迭代中获取单个值,并且无法知道您尝试测试的整个可迭代值。

@chown试图告诉你的是,你可以通过使用同学得到的答案来解决skip() ......

def skip(X):
    return len([w for w in xrange(len(X) - 2) if X[w] == X[w + 2]])

...明确

>>> def skip(X):
...     return len([w for w in xrange(len(X) - 2) if X[w] == X[w + 2]])
... 
>>> skip('evening')
2
>>> skip([1,2,3,4])
0
>>> skip([0,0,0,0,0])
3
>>> skip("onoratitatio")
3
>>>