0

R 'which' 函数是一种在长字符向量字符串中查找字符的有效且并行化的方法。有没有在python中实现这个功能或简单的方法?

4

3 回答 3

2

如果这些元素满足特定条件,则获取可枚举集合中元素索引的pythonic方法是将列表推导enumerate()一起使用。例如,要查找列表中奇数元素的所有索引:

>>> mylist = [1,2,3,4,5,6,7,8]
>>> [index for index, item in enumerate(mylist) if item%2]
[0, 2, 4, 6]
于 2013-09-16T07:41:03.503 回答
0

我不太确定 R 是如何工作的,但这里有一些想法可以帮助您入门

lookingFor = 'a'
print "the string of all '%s's is" %lookingFor, ''.join(char for char in myLongString if char==lookingFor)
print "there are %s many instances of the character '%s' in the string '%s'" %(myLongString.count(lookingFor), lookingFor, myLongString)
import collections
print "there are %s many instances of the character '%s' in the string '%s'" %(collections.Counter(myLongString)[lookingFor], lookingFor, myLongString)
于 2013-09-16T07:37:21.580 回答
0

或包装成通用函数:

>>> which = lambda targetList, f: [index for index, item in enumerate(targetList) if f(item)]

例如:

>>> mylist = [1,2,3,4,5,6,7,8]
>>> which(mylist, lambda x: x % 2)
于 2017-04-17T13:37:08.173 回答