python函数按索引拆分列表

时间:2014-04-22 06:56:50

标签: list function python-2.7 split indexing

我正在尝试构建一个有效的函数,用于按任意给定数量的索引拆分任何大小的列表。这种方法有效,我花了几个小时才能把它弄好(我讨厌在使用索引时出错是多么容易)

我是否过度思考?

代码:

def lindexsplit(List,* lindex):

index = list(lindex)

index.sort()

templist1 = []
templist2 = []
templist3 = []

breakcounter = 0
itemcounter = 0
finalcounter = 0


numberofbreaks = len(index)
totalitems = len(List)

lastindexval = index[(len(index)-1)]
finalcounttrigger = (totalitems-(lastindexval+1))

for item in List:

    itemcounter += 1

    indexofitem = itemcounter - 1

    nextbreakindex = index[breakcounter]

    #Less than the last cut
    if breakcounter <= numberofbreaks:

        if indexofitem < nextbreakindex:

            templist1.append(item)

        elif breakcounter < (numberofbreaks - 1):

            templist1.append(item)

            templist2.append(templist1)

            templist1 = []

            breakcounter +=1

        else:

            if indexofitem <= lastindexval and indexofitem <= totalitems:

                templist1.append(item)

                templist2.append(templist1)

                templist1 = []

            else:

                if indexofitem >= lastindexval and indexofitem < totalitems + 1:

                    finalcounter += 1

                    templist3.append(item)

                    if finalcounter == finalcounttrigger:

                        templist2.append(templist3)


return templist2

0 个答案:

没有答案