在python中有与R的“哪个”功能类似的功能吗?

时间:2013-09-16 07:25:56

标签: python r character which

''''函数是一种有效且并行化的方法,用于在长字符向量字符串中查找字符。有没有函数或简单的方法在python中实现它?

3 个答案:

答案 0 :(得分:2)

如果这些元素满足某个条件,则获取可枚举集合中元素索引的pythonic方法是使用list comprehensionenumerate()。例如,要查找列表中奇数元素的所有索引:

>>> mylist = [1,2,3,4,5,6,7,8]
>>> [index for index, item in enumerate(mylist) if item%2]
[0, 2, 4, 6]

答案 1 :(得分: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)

答案 2 :(得分:0)

或包装成通用函数:

PHP Fatal error:  Uncaught Google_Service_Exception: {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "Not Found"
   }
  ],
  "code": 404,
  "message": "Not Found"
 }
}

e.g:

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