• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python test_iterlen.len函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: 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'))
        # Does not apply to Jython - no tuple reuse
#         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:Alex-CS,项目名称:sonify,代码行数:20,代码来源:test_itertools.py


示例17: create_node_attrib

def create_node_attrib(parent, tag, attrib, content=''):
	'''
	创建一个新节点,带有属性
	@param parent:父节点 
	@param tag:子节点标签
	@param attrib:属性及属性值 z.B={'NUM':'123'}
	@param content:节点闭合标签里的文本内容
	'''
	element = SubElement(parent, tag, attrib)
	if len(content) != 0:
		element.text = unicode(content , "gbk") #unicode转换
	return element
开发者ID:wildparky,项目名称:spielenPipeline,代码行数:12,代码来源:xml.py


示例18: 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'))
     if test_support.check_impl_detail():
         # izip "reuses" the same tuple object each time when it can
         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:alkorzt,项目名称:pypy,代码行数:21,代码来源:test_itertools.py


示例19: index

def index(request):
    first_news = []
    first_news_list = SportNews.objects.filter(priority='NEWS_MAIN').order_by('-created_at')
    if len(first_news_list) > 0:
        news_info = {}
        news_info['title'] = first_news_list[0].title
        news_info['img'] = '/media/' + str(first_news_list[0].photo)
        first_news.append(first_news_list[0].id)
        first_news.append(news_info)
    main_news = []
    for news_prio in NEWS_PRIO:
        if news_prio[0] != 'NEWS_NORMAL' and news_prio[0] != 'NEWS_MAIN':
            main_news_list = SportNews.objects.filter(priority=news_prio[0]).order_by('-created_at')
            if len(main_news_list) > 0:
                news_info = {}
                news_info['title'] = main_news_list[0].title
                news_info['img'] = '/media/' + str(main_news_list[0].photo)
                news = []
                news.append(main_news_list[0].id)
                news.append(news_info)
                main_news.append(news)
    
    other_news_list = SportNews.objects.all().order_by('-created_at')[:20]
    other_news = []
    for other in other_news_list:
        news = []
        news.append(other.id)
        news.append(other.photo)
        news.append(other.title)
        isItemInMainNews = False
        for mainNewsItem in main_news:
            if mainNewsItem[0] == news[0]:
                isItemInMainNews = True
        if not isItemInMainNews and first_news and other.id != first_news[0]:
            other_news.append(news)
            
    return render(request,
                  'main/index.html', {'user_info': getUseInfo(request), 'navigationBar': getNavigationBar(),'side_bar': getSideBar(), 'first_news': first_news, 'main_news': main_news, 'other_news': other_news,},
                  context_instance=RequestContext(request)
                  )
开发者ID:reyhan-sadak,项目名称:sports_statistics,代码行数:40,代码来源:views.py


示例20: test_main

def test_main(verbose=None):
    testclasses = (EnumerateTestCase, SubclassTestCase, TestEmpty, TestBig, TestReversed)
    test_support.run_unittest(*testclasses)

    # verify reference counting
    import sys

    if verbose and hasattr(sys, "gettotalrefcount"):
        counts = [None] * 5
        for i in xrange(len(counts)):
            test_support.run_unittest(*testclasses)
            counts[i] = sys.gettotalrefcount()
        print counts
开发者ID:Cinnz,项目名称:python,代码行数:13,代码来源:test_enumerate.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap