当前位置: 首页>>代码示例>>Python>>正文


Python test_iterlen.len函数代码示例

本文整理汇总了Python中test.test_iterlen.len函数的典型用法代码示例。如果您正苦于以下问题:Python len函数的具体用法?Python len怎么用?Python len使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了len函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: sort

    def sort(self, data):
        
        if data == None or len(data) < 1:
            return data 
        
        print data
                
        base_value = data[0]
        left_array = []
        right_array = []
        
        for index in range(1, len(data)):
            compare_value = data[index]
            if(base_value > compare_value):
                left_array.append(compare_value)
            else:
                right_array.append(compare_value) 
        
        if len(left_array) > 1:
            sorted_array = self.sort(left_array)
            left_array = sorted_array
            
        
        if len(right_array) > 1:
            sorted_array = self.sort(right_array)
            right_array = sorted_array

        right_array.insert(0, base_value)
        left_array.extend(right_array)
        
        return left_array
开发者ID:fatmind,项目名称:yy-python,代码行数:31,代码来源:quick_sort.py

示例2: _setupCategories

 def _setupCategories(self, config):
     """Add buttons to browse between categories
     
     config -- ConfigParser containing application settings
     
     """
     #Get all button data
     lines = []
     ctr = 1
     option = ini.image + str(ctr)
     
     while(config.has_option(ini.year, option)):
         line = config.get(ini.year, option)
         lines.append(line)
         ctr += 1
         option = ini.image + str(ctr)
         
     #Create as many buttons as needed
     buttondata = zip(lines, self._years)
     
     if(len(buttondata) < len(self._years)):
         print('Warning! There are more categories than category buttons - some categories will not be shown')
         
     ctr = 0
     
     for (line, year) in buttondata:
         tb = TransparentButton(self._canvas, self._settings.generalfont, line, self._scalefactor)
         tb.setText(year)
         tb.setCommand(self._ehYear)
         tb.index = ctr
         ctr += 1
         self._activeInPreview.append(tb)
开发者ID:d98mp,项目名称:digitalasagor,代码行数:32,代码来源:playergui.py

示例3: test_tuple_reuse

 def test_tuple_reuse(self):
     if test_support.due_to_ironpython_incompatibility("implementation detail: http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20279"): 
         return
     # Tests an implementation detail where tuple is reused
     # whenever nothing else holds a reference to it
     self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq))
     self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
开发者ID:mcgilbertus,项目名称:main,代码行数:7,代码来源:test_enumerate.py

示例4: getSkuMap

def getSkuMap(url):
    content = urllib2.urlopen(url)
    
    token = "None"
    brace_level = 0 
    skuMap = [] 
    parseStock = False
    
    for line in content : 
        gbk_line = line.decode('gbk')
               
        m1 = re.search('"skuMap":', gbk_line)
        if m1 :
            token = "skuMap"
            brace_level = brace_level + 1 
            continue       
        if token == "skuMap" :
            # print brace_level , " " , gbk_line
            if brace_level == 2 : 
                m1 = re.match('.*";(.*);".*', gbk_line)
                if m1 :
                    #  We find a skumap 
                    # add a map to it 
                    skuMap.append({})
                    skuMap[len(skuMap) - 1]["index"] = m1.group(1)
                    # print len(skuMap) , " " , m1.group(1)
            
            if brace_level == 3 : 
                m1 = re.match('.*"skuId" : "([0-9]*)".*', gbk_line)
                if m1 :
                    skuMap[len(skuMap) - 1]["skuId"] = m1.group(1)
                    continue
                m1 = re.match('.*"price" : "([0-9\.]*)".*', gbk_line)
                if m1 :
                    skuMap[len(skuMap) - 1]["price"] = m1.group(1)
                    continue
                
                m1 = re.search('stock', gbk_line)
                if m1 : 
                    parseStock = True 
                    continue 
                
                if parseStock : 
                    m1 = re.match('.*"([0-9]*)".*', gbk_line)
                    if m1 :
                        skuMap[len(skuMap) - 1]["stock"] = m1.group(1)
                        parseStock = False             
                    
            if re.match(".*{.*" , gbk_line) : 
                brace_level = brace_level + 1
            if re.match(".*}.*" , gbk_line) : 
                brace_level = brace_level - 1 
            if brace_level == 0 : 
                token = "None"
    
    return skuMap
开发者ID:youxincao,项目名称:python_learn,代码行数:56,代码来源:AutoBuy.py

示例5: getXMLNode

def getXMLNode(data):
    if len(data) < 5:
        print data
        return (2, "")
    eventDict = {}
    eventDict["date"] = strip(data[0])
    eventDict["text"] = strip(data[1])
    eventDict["img"] = strip(data[2])
    eventDict["vetName"] = strip(data[3])
    eventDict["vetID"] = strip(data[4])

    isVetNode = (
        eventDict["date"] == ""
        and eventDict["text"] == ""
        and eventDict["img"] == ""
        and not eventDict["vetName"] == ""
        and not eventDict["vetID"] == ""
    )
    isEmpty = not isVetNode and eventDict["img"] == ""
    isCusLink = isCustomLink(eventDict["img"])
    isBadVetID = isCustomLink(eventDict["vetID"])
    isEmptyName = eventDict["vetName"] == ""

    if isEmpty or isCusLink or isBadVetID or isEmptyName:
        return (3, eventDict)

    if isVetNode:
        return (1, getVetNode(eventDict))
    elif eventDict["date"] == "Date":
        return (2, "")
    else:
        return (0, getEventNode(eventDict))
开发者ID:ghostmonk,项目名称:WW2-Interactive-Timeline,代码行数:32,代码来源:CSVCleaner.py

示例6: on_categoriesview_activated

 def on_categoriesview_activated(self,index):
     articulo = self.categoriesview.model().asRecord(index)
     if len(articulo)>0:
         nuevo = True
         
         for i, line in enumerate(self.editmodel.lines):
             if line.itemId == articulo [5]:
                 nuevo = False
                 fila = i
                 line = self.editmodel.lines[self.editmodel.rowCount()-1]
             
         if nuevo:       
             fila = self.editmodel.rowCount()
             self.editmodel.insertRow(fila)
             self.parent.saveAct.setEnabled(True)
             linea = self.editmodel.lines[fila]        
             linea.itemDescription = articulo[0] + " " + articulo [1]
             linea.itemPrice = Decimal(articulo[2])
             linea.itemId = articulo[5]
             
             linea.quantityperbox = int(articulo[3])
         
         
         self.editmodel.lines[fila].quantity += 1
         self.editmodel.lines[fila].existencia  = int(articulo[4]) - self.editmodel.lines[fila].quantity 
         indice =self.editmodel.index( fila,2)
         self.editmodel.dataChanged.emit( indice, indice )
         indice =self.editmodel.index( fila,3)
         self.editmodel.dataChanged.emit( indice, indice )
         indice =self.editmodel.index( fila,5)
         self.editmodel.dataChanged.emit( indice, indice )
开发者ID:joseanm,项目名称:pyqt_billing,代码行数:31,代码来源:factura.py

示例7: remove_adjacent

def remove_adjacent(nums):
  listx = []
  for num in nums:
    from test.test_iterlen import len
    if len(listx) == 0 or num != listx[-1]:
      listx.append(num)
  return listx
开发者ID:elbuo8,项目名称:PythonSnips,代码行数:7,代码来源:list2.py

示例8: verbing

def verbing(s):
  from test.test_iterlen import len
  if len(s) < 3:
    return s
  if s[-3:] == "ing":
    return s + "ly"
  else:
    return s + "ing"
开发者ID:elbuo8,项目名称:PythonSnips,代码行数:8,代码来源:string2.py

示例9: test_izip

 def test_izip(self):
     ans = [(x, y) for x, y in izip("abc", count())]
     self.assertEqual(ans, [("a", 0), ("b", 1), ("c", 2)])
     self.assertEqual(list(izip("abc", range(6))), zip("abc", range(6)))
     self.assertEqual(list(izip("abcdef", range(3))), zip("abcdef", range(3)))
     self.assertEqual(take(3, izip("abcdef", count())), zip("abcdef", range(3)))
     self.assertEqual(list(izip("abcdef")), zip("abcdef"))
     self.assertEqual(list(izip()), zip())
     self.assertRaises(TypeError, izip, 3)
     self.assertRaises(TypeError, izip, range(3), 3)
     # Check tuple re-use (implementation detail)
     self.assertEqual([tuple(list(pair)) for pair in izip("abc", "def")], zip("abc", "def"))
     self.assertEqual([pair for pair in izip("abc", "def")], zip("abc", "def"))
     ids = map(id, izip("abc", "def"))
     self.assertEqual(min(ids), max(ids))
     ids = map(id, list(izip("abc", "def")))
     self.assertEqual(len(dict.fromkeys(ids)), len(ids))
开发者ID:arianepaola,项目名称:tg2jython,代码行数:17,代码来源:test_itertools.py

示例10: battleToSinglePC

    def battleToSinglePC(self, enemy, battleType = 1, timeLimit = 1800):
        timeLeft = timeLimit
        dataList = []
        infoFighter = []
        infoEnemy = [enemy.getCommonValues_delta().copy()]
        fighterWin = False
        for item in self.getMyTeamInfomation():
            if item['type'] == 1: #PlayerCharacter object
                player = PlayersManager().getPlayerByID(item['id'])
                if player is None:
                    player = PlayersManager().createPlayerByID(item['id'])
                data = player.battle.fightTo(enemy, battleType, timeLeft)
                dataList.append(data)
                timeLeft -= data['overTime']
                if data["winner"] != enemy.getBaseID():
                    fighterWin = True
                    break
                infoFighter.append(player.getCommonValues_delta().copy())
            elif item["type"] == 2:
                pass

        overTime = 0
        HPMPDelta = []
        result = []

        startTime = 0
        uL = dataList[-1]['battleEventProcessList'][-1]
        for i in dataList:
            i['battleEventProcessList'].pop(0)
            i['battleEventProcessList'].pop(-1)
            for e in i['battleEventProcessList']:
                e[0] += startTime
            for d in i["MPHPDelta"]:
                d["time"] += startTime
            result += i['battleEventProcessList']
            HPMPDelta += i["MPHPDelta"]
            startTime += i["overTime"]

        # create end event
        if fighterWin:
            battleResult_set = []
            result_i = [] #{}
            for i in range(len(infoFighter)):
                battleResult_set.append({'id':infoFighter[i]['id'], 'battleResult':result_i[i]})

            event = [overTime, 2, -1, battleResult_set]

        import datetime
        result.insert(0, [0, 1, -1, [infoFighter, infoEnemy, str(datetime.datetime.now())]])
        data = {}
        data['battleType'] = battleType
        data['maxTime'] = timeLimit
        data['timeLimit'] = timeLimit
        data['battleEventProcessList'] = result
        data['MPHPDelta'] = HPMPDelta#记录每秒玩家双方hp/mp增量
        data['overTime'] = overTime
        return data
        return
开发者ID:freedream520,项目名称:sanguogame,代码行数:58,代码来源:CharacterTeamComponent.py

示例11: checkIfPasswordIsValid

def checkIfPasswordIsValid(password):
    if len(password) < 10:
        return False
    elif not checkIfStringContainsDigit(password):
        return False
    elif not CheckIfStringContainsCapitalLetter(password):
        return False
    else:
        return True
开发者ID:reyhan-sadak,项目名称:sports_statistics,代码行数:9,代码来源:views.py

示例12: test_len

 def test_len(self):
     # This is an implementation detail, not an interface requirement
     from test.test_iterlen import len
     for s in ('hello', tuple('hello'), list('hello'), range(5)):
         self.assertEqual(len(reversed(s)), len(s))
         r = reversed(s)
         list(r)
         self.assertEqual(len(r), 0)
     class SeqWithWeirdLen:
         called = False
         def __len__(self):
             if not self.called:
                 self.called = True
                 return 10
             raise ZeroDivisionError
         def __getitem__(self, index):
             return index
     r = reversed(SeqWithWeirdLen())
     self.assertRaises(ZeroDivisionError, len, r)
开发者ID:henrywoo,项目名称:Python3.1.3-Linux,代码行数:19,代码来源:test_enumerate.py

示例13: test_main

def test_main(verbose=None):
    support.run_unittest(__name__)

    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in range(len(counts)):
            support.run_unittest(__name__)
            counts[i] = sys.gettotalrefcount()
        print(counts)
开发者ID:henrywoo,项目名称:Python3.1.3-Linux,代码行数:10,代码来源:test_enumerate.py

示例14: test_cycle

 def test_cycle(self):
     for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
         for g in (G, I, Ig, S, L, R):
             tgtlen = len(s) * 3
             expected = list(g(s))*3
             actual = list(islice(cycle(g(s)), tgtlen))
             self.assertEqual(actual, expected)
         self.assertRaises(TypeError, cycle, X(s))
         self.assertRaises(TypeError, list, cycle(N(s)))
         self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
开发者ID:Alex-CS,项目名称:sonify,代码行数:10,代码来源:test_itertools.py

示例15: create_node

def create_node(parent, tag, content='',):
	'''
	创建一个新节点
	@param parent:父节点 
	@param tag:子节点标签
	@param content:节点闭合标签里的文本内容
	'''
	element = SubElement(parent, tag)
	if len(content) != 0:
		element.text = unicode(content , "gbk") #unicode转换
	return element
开发者ID:wildparky,项目名称:spielenPipeline,代码行数:11,代码来源:xml.py


注:本文中的test.test_iterlen.len函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。